Replace the Substring for Balanced String

MediumSliding Windowsliding window

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given a string s of length n using only the characters Q, W, E and R, where n is a multiple of 4. The string is *balanced* when each of the four characters appears exactly n / 4 times. You may pick one contiguous substring and replace it with any string of the same length. Return the minimum length of a substring whose replacement can make s balanced. Return 0 if s is already balanced.

Examples

Input: s = "QWER"
Output: 0
Each character appears once already.
Input: s = "QQWE"
Output: 1
Replace one `Q` with `R`.
Input: s = "QQQW"
Output: 2
Replace `"QQ"` with `"ER"`.

Constraints

  • 4 <= s.length <= 10^5
  • s.length is a multiple of 4
  • s contains only `Q`, `W`, `E`, `R`

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More sliding window problems