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 String INPUT String s = "QWER" Q W E R 0 1 2 3 Character Counts Char Count Target Q 1 1 W 1 1 E 1 1 R 1 1 n = 4, target = n/4 = 1 ALGORITHM STEPS 1 Count Characters Count Q, W, E, R in string 2 Check Balance All chars = n/4? Return 0 3 Sliding Window Find min substring to fix 4 Return Result Min window length found Balance Check Q: 1 == 1 OK W: 1 == 1 OK E: 1 == 1 OK R: 1 == 1 OK FINAL RESULT String is already balanced! Q W E R Each char appears exactly 1 time (n/4 = 4/4 = 1) Output 0 No replacement needed Min substring length = 0 BALANCED Key Insight: Use sliding window technique to find the minimum substring to replace. The window should contain excess characters (count greater than n/4). Shrink window from left while maintaining validity. For balanced input like "QWER", all counts equal n/4, so no replacement needed --> return 0. TutorialsPoint - Replace the Substring for Balanced String | Optimal Solution (Sliding Window)
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