The Replace the Substring for Balanced String interview question gives you a string of length n containing only the characters 'Q', 'W', 'E', and 'R'. A balanced string has exactly n/4 of each character. You can replace any contiguous substring with any characters. Find the minimum length of such a substring replacement that can make the entire string balanced.
This problem is asked at Amazon because it demonstrates the sliding window technique applied to a balance/frequency constraint. It is a non-obvious application: the key insight is that if the characters outside the window already satisfy balance requirements (none exceeds n/4), then the window can be filled arbitrarily to balance the rest. This pattern tests advanced sliding window reasoning beyond simple sum or product windows.
The pattern is sliding window with frequency tracking. The target count for each character is n/4. Count all characters in the string. Use a sliding window [left, right] that expands and contracts. The window represents the substring to be replaced. A window is valid when all characters OUTSIDE the window have frequency ≤ n/4 (meaning the window contains enough "excess" characters that when replaced, balance is achievable). Minimize the valid window size.
String: "QWER" (n=4, target=1 each). All already balanced. Minimum replacement length = 0.
String: "QQWE" (n=4, target=1 each). Q appears 2 times — excess 1.
Minimum replacement: 1 (replace one 'Q' with 'R').
String: "WQWRQQQW" (n=8, target=2 each). Q=4 (excess 2), W=3 (excess 1).
n must be divisible by 4 (guaranteed by the problem, but worth verifying).For the Replace the Substring for Balanced String coding problem, the sliding window and string interview pattern is the key. The counter-intuitive part is checking the OUTSIDE of the window for balance. Interviewers at Amazon appreciate when you state this insight clearly before coding: "The window is valid when no character outside it exceeds n/4." Practice shrinking the window from the left after each valid configuration to find the minimum length.