class Solution {
private:
bool check(vector<int>& cnts, int len, int require) {
int totalAdjustments = 0;
for (int i = 0; i < 4; i++) {
if (cnts[i] > require) return false;
totalAdjustments += max(0, require - cnts[i]);
}
return totalAdjustments <= len;
}
public:
int balancedString(string s) {
int n = s.size();
vector<int> arr(n);
vector<int> cnts(4, 0);
for (int i = 0; i < n; i++) {
if (s[i] == 'Q') arr[i] = 0;
else if (s[i] == 'W') arr[i] = 1;
else if (s[i] == 'E') arr[i] = 2;
else if (s[i] == 'R') arr[i] = 3;
cnts[arr[i]]++;
}
int require = n / 4;
int res = n;
for (int left = 0, right = 0; left < n; left++) {
while (right < n && !check(cnts, right - left, require)) {
cnts[arr[right]]--;
right++;
}
if (check(cnts, right - left, require)) {
res = min(res, right - left);
}
cnts[arr[left]]++;
}
return res;
}
};