Replace the Substring for Balanced String - Problem

You are given a string s of length n containing only four kinds of characters: 'Q', 'W', 'E', and 'R'.

A string is said to be balanced if each of its characters appears n / 4 times where n is the length of the string.

Return the minimum length of the substring that can be replaced with any other string of the same length to make s balanced.

If s is already balanced, return 0.

Input & Output

Example 1 — String with Excess Q
$ Input: s = "QWER"
Output: 0
💡 Note: String length is 4, each character appears exactly 1 time = 4/4, so it's already balanced
Example 2 — Need to Replace Substring
$ Input: s = "QQWE"
Output: 1
💡 Note: Q appears 2 times, W appears 1 time, E appears 1 time, R appears 0 times. Target is 1 each. Need to replace 1 Q with R, so minimum length is 1
Example 3 — Larger Imbalance
$ Input: s = "QQQQQWWW"
Output: 4
💡 Note: Length 8, target is 2 each. Q appears 5 times (3 excess), W appears 3 times (1 excess), E and R appear 0 times each. Need to replace a substring containing at least 3 Q's and 1 W, minimum length is 4

Constraints

  • 1 ≤ s.length ≤ 105
  • s.length is a multiple of 4
  • s consists of only 'Q', 'W', 'E', and 'R'

Visualization

Tap to expand
Replace Substring for Balanced StringInput: "QQWE" → Target: 1 each characterQQWEexcessexcessokokCount: Q=2, W=1, E=1, R=0Q appears 2 times, need 1 → 1 excess QMin window: 1Replace 1 character: Q → RResult: 1
Understanding the Visualization
1
Input Analysis
Count frequency of Q, W, E, R characters
2
Find Excess
Identify characters appearing more than n/4 times
3
Minimum Window
Find smallest substring containing all excess characters
Key Takeaway
🎯 Key Insight: Only excess characters need replacement - find the minimum window containing all excess using sliding window technique
Asked in
Facebook 15 Google 12 Microsoft 8
28.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen