Python 1189.py
class Solution:
def maxNumberOfBalloons(self, text: str) -> int:
freq = defaultdict(int)
for t in text:
freq[t] += 1
result = min(freq["b"], freq["a"])
result = min(result, freq["n"])
result = min(result, freq["l"] // 2)
result = min(result, freq["o"] // 2)
return result
Difficulty
and has an acceptance rate of about 64% (700k+ submissions).
Typical patterns to solve this problem:
- Counting
- Hash Table
- 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 defines a class Solution with a single method maxNumberOfBalloons. The method receives a string text and computes how many times the word balloon can be assembled from the characters in text. It does this by counting the occurrences of each character, then determining the limiting factor among the required letters, taking into account that some letters appear more than once in the target word.
Key Steps
Counting character frequencies
The method begins by creating a frequency map using a defaultdict that defaults to zero. It iterates over each character in the input string and increments the corresponding count.
freq = defaultdict(int)
for t in text:
freq[t] += 1
This step builds a complete histogram of the characters present in text. By using defaultdict(int), the code avoids explicit existence checks for each key, which streamlines the counting loop.
Determining the limiting count
After the histogram is built, the method calculates the maximum number of complete “balloon” words that can be formed. It starts with the minimum of the counts for the letters that appear once in the target word, namely 'b', 'a', and 'n'. The result is then refined by considering the letters that appear twice, 'l' and 'o'. For these, the stored count is divided by two before taking the minimum.
result = min(freq["b"], freq["a"])
result = min(result, freq["n"])
result = min(result, freq["l"] // 2)
result = min(result, freq["o"] // 2)
Each min call narrows the possible number of balloons to the most restrictive letter count. The division by two for 'l' and 'o' correctly reflects the requirement of two occurrences of each of those letters per balloon.
Returning the final answer
The method concludes by returning the computed result, which represents the maximum number of times the word “balloon” can be constructed from the supplied characters.
return result
Edge Cases Handled
When the input string lacks any of the required letters, the corresponding entry in the frequency map defaults to zero. The min operations naturally yield zero in such scenarios, causing the method to return zero balloons, which is the correct outcome.
If the input contains an excess of letters that are not part of the word “balloon”, those characters are simply ignored because they never influence the min calculations.
For inputs where the counts of 'l' or 'o' are odd, the integer division (// 2) discards the leftover single occurrence, ensuring that only complete pairs contribute to the balloon count.
The method also gracefully handles an empty string: the frequency map remains empty, all lookups return zero, and the final result is zero.
Performance Optimizations
The use of defaultdict(int) eliminates the need for conditional checks when updating the frequency map, reducing overhead in the counting loop.
The algorithm performs a single pass over the input string to build the histogram, which minimizes the number of iterations required.
Subsequent calculations use a constant number of min operations and integer divisions, avoiding any additional loops or data structures. This constant-time post-processing ensures that the overall runtime scales linearly with the length of the input string, without any hidden multiplicative factors.
By directly accessing the needed keys ("b", "a", "n", "l", "o"), the code avoids scanning the entire frequency map, further keeping the work bounded to a small, fixed set of operations after the initial pass.
ELI5 - Simplified Explanation
Imagine you have a big bucket full of letter blocks and you want to see how many times you can spell the word balloon. First, you look through all the blocks in the bucket and count how many of each letter you have. You need one b, one a, two ls, two os, and one n to make a single balloon.
Once you know your counts, you check how many full sets of letters you can put together. You look at the letters one by one to see which one runs out first because that decides how many balloons you can finish building. Even if you have lots of some letters, you can only make as many balloons as your rarest required letter allows. If you need two letters to make a balloon, like the l or the o, you divide your count in half to see how many pairs you have. After checking all the groups, the smallest number tells you exactly how many balloons you can build.
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 | PHP | Rust | TS | |||||
| Progiez | C++ | Python | Java | |||||||||
| github | BigEggStudy | C# | ||||||||||
| black-shadows | C++ | |||||||||||
| charles-wangkai | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JS | |||||||||||
| fartem | Ruby | |||||||||||
| fpdjsns | C++ | |||||||||||
| fsq | C++ | |||||||||||
| Garvit244 | Python | |||||||||||
| halfrost | Go | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| lzl124631x | C++ | |||||||||||
| qiyuangong | Java | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| withaarzoo | C++ | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, Go, Java, PHP, Python, Rust, TypeScript | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| charles-wangkai | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JavaScript | |||||||||||
| fartem | Ruby | |||||||||||
| fpdjsns | C++ | |||||||||||
| fsq | C++ | |||||||||||
| Garvit244 | Python | |||||||||||
| halfrost | Go | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| lzl124631x | C++ | |||||||||||
| qiyuangong | Java | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| withaarzoo | C++ | |||||||||||
| YuriSpiridonov | Python |
Videos
Solved On The Same Day
- problem 929: Unique Email Addresses
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