Replace the Substring for Balanced String Problem
Description
LeetCode Problem 1234.
You are given a string s of length n containing only four kinds of characters: 'Q', 'W', 'E', and 'R'.
A string is said to be balanced if each of its characters appears n / 4 times where n is the length of the string.
Return the minimum length of the substring that can be replaced with any other string of the same length to make s balanced. If s is already balanced, return 0.
Example 1:
Input: s = "QWER"
Output: 0
Explanation: s is already balanced.
Example 2:
Input: s = "QQWE"
Output: 1
Explanation: We need to replace a 'Q' to 'R', so that "RQWE" (or "QRWE") is balanced.
Example 3:
Input: s = "QQQW"
Output: 2
Explanation: We can replace the first "QQ" to "ER".
Constraints:
n == s.length4 <= n <= 10^5nis a multiple of4.scontains only'Q','W','E', and'R'.
Solution
Approach: Sliding Window Over the Part We Replace
Let m = n / 4. We may rewrite one substring however we like, so only the characters outside it are fixed. The rest of the string can be made balanced exactly when no letter appears more than m times outside the window: then the window can be filled with whatever each letter still lacks. The window is exactly long enough for that: the letters lack 4m minus the number of characters outside in total, which is the window length.
So the answer is the shortest window whose outside has every count <= m. A larger window only removes characters from the outside, so if a window works, every window containing it works too. That makes a two-pointer sliding window correct:
- Count all four letters in
s. If every count is already<= m, the string is balanced and the answer is0. - Move the right end
iover the string; each step takess[i]out of the outside counts. - While the outside counts are all
<= m, the windows[j..i]works: record its length, then gives[j]back to the outside and movejright to look for a shorter one.
Each pointer only moves forward, so the scan is linear. The j <= i guard stops the window from shrinking below empty.
Complexity: O(n) time and O(1) extra space (four counters).
from collections import Counter
class Solution:
def balancedString(self, s: str) -> int:
n = len(s)
m = n // 4
cnt = Counter(s) # counts of the letters outside the window
if all(cnt[c] <= m for c in "QWER"):
return 0
ans, j = n, 0
for i, c in enumerate(s):
cnt[c] -= 1 # s[i] joins the window s[j..i]
# While the letters left outside need no fixing, shrink the window from the left.
while j <= i and all(cnt[c] <= m for c in "QWER"):
ans = min(ans, i - j + 1)
cnt[s[j]] += 1
j += 1
return ans