#1234
Replace the Substring for Balanced String
MediumStringSliding WindowSliding WindowTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution uses a sliding window approach to efficiently find the minimum length of the substring that can be replaced. This method allows us to maintain a window of characters and adjust it dynamically, ensuring we only check necessary parts of the string.
⚙️
Algorithm
6 steps- 1Step 1: Count the occurrences of each character in the string.
- 2Step 2: Calculate the target count for each character (n / 4).
- 3Step 3: Use two pointers to create a sliding window over the string.
- 4Step 4: Expand the right pointer to include characters until the window is valid (all characters are within the target count).
- 5Step 5: Once valid, move the left pointer to minimize the window size while maintaining validity.
- 6Step 6: Track the minimum length of the valid window.
solution.py16 lines
1def balancedString(s):
2 from collections import Counter
3 n = len(s)
4 target = n // 4
5 count = Counter(s)
6 if all(count[c] == target for c in 'QWER'):
7 return 0
8 left = 0
9 min_length = n
10 for right in range(n):
11 count[s[right]] -= 1
12 while all(count[c] <= target for c in 'QWER'):
13 min_length = min(min_length, right - left + 1)
14 count[s[left]] += 1
15 left += 1
16 return min_lengthℹ
Complexity note: The time complexity is O(n) because we traverse the string with two pointers, ensuring each character is processed a limited number of times. The space complexity is O(1) as we only use a fixed-size array for counting characters.
- 1A string is balanced when each character appears exactly n/4 times.
- 2Using a sliding window allows us to efficiently find the minimum substring to replace.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.