↓Skip to main content
  1. LeetCode/

LeetCode 1234: Replace the Substring for Balanced String

·2 mins· ·
LeetCode Medium Sliding-Window String
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2026-01-18

  • Submissions: Accepted (first try)

Approach
#

Replacing the window leaves the characters outside it untouched. For the whole string to balance, each character outside must be <= n / 4 (only then can the window make up the rest).

Conversely, whenever every character outside is <= n / 4, the window can always be filled to balance. So:

  • Keep outside[c], the count outside the window.
  • Use the “shortest” sliding window: add on the right (outside minus one), update the answer while valid, then try shrinking the left (outside plus one).

If the string is already balanced, the answer is 0.

My Solution
#

class Solution:
    def balancedString(self, s: str) -> int:
        n = len(s)
        target = n // 4
        outside = Counter(s)                       # counts outside the window
        if all(outside[c] <= target for c in "QWER"):
            return 0

        left = 0
        best = n
        for right, c in enumerate(s):
            outside[c] -= 1
            while left <= right and all(outside[ch] <= target for ch in "QWER"):
                best = min(best, right - left + 1)
                outside[s[left]] += 1
                left += 1
        return best

My original first computed how many extra copies of each character there were, required the window to contain those extras, and used meet_count to track how many kinds were covered. It means the same thing, but “nothing outside exceeds n / 4” is shorter.

Complexity
#

Time O(n) (4 characters checked each time), space O(1).

Mistakes to Avoid
#

  • Return 0 when the string is already balanced.
  • The validity check is about outside the window, not inside.

Interview Explanation
#

Replacing a block leaves everything outside it unchanged, so the string can be balanced exactly when each character outside appears at most n / 4 times. I track the counts outside the window with a shortest-window slide, updating the answer while valid and then shrinking the left. If it is balanced from the start, return 0. Time O(n).

Related

LeetCode 2730: Find the Longest Semi-Repetitive Substring
·2 mins
LeetCode Medium Sliding-Window String
LeetCode 2730 note: the window holds at most one adjacent equal pair; when a new pair arrives, shrink the left until the previous pair leaves
LeetCode 1208: Get Equal Substrings Within Budget
·1 min
LeetCode Medium Sliding-Window String Binary-Search Prefix-Sum
LeetCode 1208 note: each position costs |s[i] - t[i]|, so the problem becomes the longest subarray with sum <= maxCost
LeetCode 2024: Maximize the Confusion of an Exam
·2 mins
LeetCode Medium Sliding-Window String Binary-Search Prefix-Sum
LeetCode 2024 note: a window is valid when the rarer of T and F appears at most k times (flip all of them); shrink the left when it is not
LeetCode 2904: Shortest and Lexicographically Smallest Beautiful String
·2 mins
LeetCode Medium Sliding-Window String
LeetCode 2904 note: with exactly k ones in the window, also shrink away leading zeros to get the shortest beautiful substring ending at right; compare by length first, then lexicographically
LeetCode 395: Longest Substring with At Least K Repeating Characters
·3 mins
LeetCode Medium Sliding-Window Divide-and-Conquer Hash-Table String
LeetCode 395 note: “every character at least k times” is not monotonic, so a direct slide fails; divide and conquer splits on characters with fewer than k occurrences, or fixing the number of distinct characters makes the window slidable
LeetCode 2516: Take K of Each Character From Left and Right
·2 mins
LeetCode Medium Sliding-Window Hash-Table String
LeetCode 2516 note: taking from both ends leaves a middle block in which each letter may appear at most total − k times; find the longest such window