Skip to content

Latest commit

 

History

History
52 lines (36 loc) · 1014 Bytes

File metadata and controls

52 lines (36 loc) · 1014 Bytes

Replace the Substring for Balanced String

Problem Link

https://leetcode.com/problems/replace-the-substring-for-balanced-string/


Pattern

  • Sliding Window

Approach

Find minimum window where replacing makes all characters equal; use frequency tracking.


Time Complexity

O(n)

Space Complexity

O(1)


Java Solution

class Solution {
    public int balancedString(String s) {
        int n = s.length(), target = n / 4;
        int[] count = new int[26];
        for (char c : s.toCharArray()) count[c - 'A']++;
        int left = 0, ans = n;
        for (int right = 0; right < n; right++) {
            count[s.charAt(right) - 'A']--;
            while (count['Q'-'A'] <= target && count['W'-'A'] <= target &&
                   count['E'-'A'] <= target && count['R'-'A'] <= target) {
                ans = Math.min(ans, right - left + 1);
                count[s.charAt(left) - 'A']++;
                left++;
            }
        }
        return ans;
    }
}