You are given a string s containing only four specific characters: 'Q', 'W', 'E', and 'R'. Think of this as a special encoding where each character must appear in perfect balance.
A string is considered balanced if each of the four characters appears exactly n/4 times, where n is the total length of the string. Your goal is to find the minimum length substring that you can replace with any other string of the same length to make the entire string balanced.
Example: If s = "QWER", it's already balanced (each character appears once). If s = "QQWE", you need to replace at least one character to balance it.
Return 0 if the string is already balanced, otherwise return the minimum replacement length needed.
Input & Output
Visualization
Time & Space Complexity
Single pass through the string with each character visited at most twice (once by right pointer, once by left pointer)
Only using constant extra space for character counters and pointers
Constraints
- 1 โค n โค 105
- n is divisible by 4
- s consists only of 'Q', 'W', 'E', and 'R'
- Note: Since n must be divisible by 4, n/4 is always an integer