Replace the Substring for Balanced String — LeetCode 1234 Python Solution
- Problem
- #1234
- Pattern
- Sliding Window
- Reading time
- 3 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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.