Problem Description
Given a string s of length n containing only the characters 'Q', 'W', 'E', and 'R', a string is balanced if each character appears exactly n/4 times. The task is to find the minimum length of a contiguous substring that can be replaced with any other string of the same length to make s balanced. If s is already balanced, return 0.
Key Insights
- Count the frequency of each character in the string.
- Determine the excess count for characters that appear more than n/4 times.
- Use a sliding window to identify the smallest substring such that when replaced, the rest of the string meets the balance criteria.
- If the string is already balanced (i.e., all counts are exactly n/4), the answer is 0.
- The sliding window approach ensures we find the minimum replacement window efficiently.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(1) (only using a fixed-size dictionary/array for 4 characters)
Solution
The solution first calculates the count of each character and checks for excess above the target (n/4). Using a sliding window, we progressively reduce the count of characters as we move the right pointer. When the remaining characters (outside the window) satisfy the balance requirement (each count is ≤ n/4), the current window is a valid candidate for replacement. Then, we try to shrink this window from the left to find the minimum possible length that still meets the valid condition. This minimum length is the answer.