Replace the Substring for Balanced String — LeetCode 1234 Python Solution

MediumStringSliding Window
Problem
#1234
Reading time
3 min

The 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.

Example

Input
s = "QWER"
Output
0
Explanation
s is already balanced.

Python solution

Python
class Solution:
    def balancedString(self, s: str) -> int:
        cnt = Counter(s)
        n = len(s)
        if all(v <= n // 4 for v in cnt.values()):
            return 0
        ans, j = n, 0
        for i, c in enumerate(s):
            cnt[c] -= 1
            while j <= i and all(v <= n // 4 for v in cnt.values()):
                ans = min(ans, i - j + 1)
                cnt[s[j]] += 1
                j += 1
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(C) auxiliary

Pattern: Sliding Window

Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 1234. Replace the Substring for Balanced String is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.

The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1234. Replace the Substring for Balanced String?
LeetCode 1234. Replace the Substring for Balanced String is rated Medium on LeetCode.
What is the time complexity of LeetCode 1234. Replace the Substring for Balanced String?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1234. Replace the Substring for Balanced String?
The Python solution on this page uses O(C) auxiliary space.
What topics does LeetCode 1234. Replace the Substring for Balanced String cover?
LeetCode 1234. Replace the Substring for Balanced String is tagged String and Sliding Window on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview