Python 1234.py
class Solution:
def balancedString(self, s: str) -> int:
result = size = len(s)
expected = size // 4 # how often Q, W, E and R should be found (if balanced)
# fun fact regarding the ASCII codes of Q, W, E, R:
# if we ignore the lowest bit, then the next two lowest bits are Q => 00, W => 11, E => 10, R => 01
# that's perfect for indexing a simple array !
index = lambda x : (ord(x) >> 1) & 3
# Q R E W
freq = [ 0, 0, 0, 0 ]
for c in s:
freq[index(c)] += 1
# yet another sliding window
left = 0
for right, c in enumerate(s):
freq[index(c)] -= 1 # enlarge substring
# if still balanced, then shrink substring
while left < size and max(freq) <= expected:
result = min(result, right - left + 1)
freq[index(s[left])] += 1
left += 1
return result
Difficulty
and has an acceptance rate of about 41% (100k+ submissions).
Typical patterns to solve this problem:
- Sliding Window
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the problem of finding the smallest contiguous substring that can be replaced so that the four characters Q, W, E, R appear the same number of times in the whole string. The algorithm first determines how many times each character should appear in a perfectly balanced string, then records the current frequencies, and finally uses a sliding-window technique to shrink a candidate substring while the remaining part of the string stays within the required limits. The result is the length of the minimal substring that satisfies the condition.
Key Steps
Determining the target frequency
result = size = len(s)
expected = size // 4 # how often Q, W, E and R should be found (if balanced)
The variable expected holds the ideal count for each character when the string is balanced. The initial result is set to the full length of the input, representing the worst-case scenario where the whole string must be replaced.
Mapping characters to array indices with bit manipulation
index = lambda x : (ord(x) >> 1) & 3
# Q R E W
freq = [0, 0, 0, 0]
A compact lambda expression converts a character into an index between 0 and 3 by discarding the lowest bit of its ASCII code and then extracting the next two bits. This mapping aligns Q, R, E, W to positions 0-3 respectively, allowing the algorithm to use a fixed-size list freq for counting instead of a dictionary.
Counting the initial frequencies
for c in s:
freq[index(c)] += 1
A single pass over the input populates freq with the total occurrences of each character. Because the array size is constant, this step runs quickly and uses minimal memory.
Expanding the sliding window
left = 0
for right, c in enumerate(s):
freq[index(c)] -= 1 # enlarge substring
The outer loop moves the right boundary of the window forward one character at a time. Decrementing the frequency of the newly included character reflects the fact that this character is now part of the candidate substring to be replaced.
Contracting the window while the remaining string stays balanced
while left < size and max(freq) <= expected:
result = min(result, right - left + 1)
freq[index(s[left])] += 1
left += 1
Inside the while loop the algorithm checks whether the frequencies of the characters outside the current window are all at most expected. The condition max(freq) <= expected guarantees that the remaining part of the string already satisfies the balance requirement. When this holds, the current window length (right - left + 1) is a candidate for the answer, and the algorithm attempts to shrink the window from the left side, restoring the frequency of the character that leaves the window.
Returning the minimal length
return result
After the right boundary has traversed the entire string, result contains the length of the smallest substring whose replacement yields a balanced string.
Edge Cases Handled
The algorithm gracefully deals with an empty input because size becomes zero, expected is zero, and the outer loop never executes, leaving result as zero, which is the correct answer. When the input string is already balanced, the initial frequency counts already satisfy max(freq) <= expected. The inner while loop will immediately shrink the window to size one, then to zero, updating result to zero, indicating that no replacement is needed. If the string consists of a single repeated character, the frequency of that character will exceed expected until the sliding window eventually covers the entire string, causing result to become the full length, which is the only viable replacement length. For strings whose length is not a multiple of four, integer division yields the floor of the ideal count; the condition max(freq) <= expected still correctly identifies when the remaining characters are within the permissible range, leading the algorithm to replace the necessary excess characters.
Performance Optimizations
The code leverages a fixed-size list of four integers for frequency tracking, eliminating the overhead of hash-based structures. The custom index lambda uses bitwise operations to compute array positions in constant time, avoiding conditional branches or look-up tables. Updating frequencies during window expansion and contraction is performed in place, which keeps the memory footprint minimal. The use of max(freq) operates on a four-element list, making the check inexpensive even though it is executed repeatedly. Overall, the sliding-window approach ensures that each character is processed a constant number of times, resulting in a highly efficient solution for large inputs.
ELI5 - Simplified Explanation
Imagine you have a long string of letter blocks decorated with the letters Q, W, E, and R. The goal is to make sure each letter appears exactly the same number of times so that everything is perfectly balanced.
To start, the program counts every single letter in the line to see how many of each are currently there. It figures out how many times each letter should ideally show up by dividing the total number of blocks by four.
The program then uses a trick called a sliding window to find the smallest group of letters in the middle that needs to be changed. It stretches a window out by moving the right side one letter at a time, looking at which letters are inside. Every time a letter is added into the window, the count of available letters outside drops.
Whenever the letters remaining outside are balanced, the program tries to shrink the window from the left side to see just how small it can get while still keeping things fair. It keeps track of the smallest window size it finds during this process so it knows the best way to fix the balance.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||
|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||
| WalkCCC | C++ | Python | Java | |||||
| leetcode.ca | C++ | Python | Java | Go | ||||
| MemoryLimitExceeded | C++ | Python | ||||||
| Progiez | C++ | Python | Java | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| fsq | C++ | |||||||
| halfrost | Go | |||||||
| JoshCrozier | JS | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| wisdompeak | C++ | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, Go, Java, Python | |||||||
| MemoryLimitExceeded | Python, C++ | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| fsq | C++ | |||||||
| halfrost | Go | |||||||
| JoshCrozier | JavaScript | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| wisdompeak | C++ |
Videos
Solved On The Same Day
- problem 1233: Remove Sub-Folders from the Filesystem
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality