class Solution:
def balancedString(self, s: str) -> int:
"""
tc O(N) sc O(1) since only cnt 4 char QWER
note,only 4 types of char
main idea: two pointer--- instead of checking if substring within the window is balanced, we check substring count outside window if by adding them into window (replaced into desired character) ===> as only as we make substring's cnt in the window all have spare space to allow substring outside window to add in.
e.g.
n = 12 n/4 = 3
WWQQRRRRQRQQ
l r
^ ^
| 4 |
"""
n = len(s)
k = n//4
l = 0
res = n
d = {}
cnt = Counter(s)
for r in range(n):
cnt[s[r]] -= 1
while l < n and all(cnt[c]<=k for c in 'QWER'):
res = min(res,r-l+1)
cnt[s[l]] += 1
l += 1
return res