#1234
Replace the Substring for Balanced String
expert · 1015 · lc medium +32 · verified · 40.6% accepted · 1,284 likes · top 20%
Description
You have a string s of length n consisting only of 'Q', 'W', 'E', and 'R'.
A string is balanced when each of these four characters appears exactly n / 4 times.
Find the minimum length of a contiguous substring that, if replaced with any string of the same length, would make s balanced. Return 0 if s is already balanced.
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".
Code
1
2
3