Description
You are given a string s of length n containing only Q, W, E, R. A string is balanced if each character occurs n/4 times. Return the minimum length of the substring that can be replaced to make s balanced.
Examples
s = "QWER"0Already balanced.
s = "QQQWWWEE"4The string has length 8, so each character should appear 2 times. Currently: Q=3, W=3, E=2, R=0. There are 1 excess Q, 1 excess W, and need 2 R's. The minimum substring to replace must contain at least the excess characters and allow space for the missing ones. The substring "QWWW" (length 4) can be replaced with "WRER" to make the string balanced.
s = "QQQQWWWWEEERRR"2The string has length 14, but since n must be a multiple of 4, this would be invalid. Let me correct: s = "QQQQWWWWEEERRRRR" has length 16, so each character should appear 4 times. Currently: Q=4, W=4, E=3, R=5. There are 1 excess R and need 1 E. The minimum substring "RR" (length 2) at the end can be replaced with "RE" to balance the string.
Constraints
- •
4 ≤ n ≤ 10^5 - •
n is a multiple of 4