#1189
Maximum Number of Balloons
EasyHash TableStringCountingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a frequency count of the characters in the string and calculates how many times we can form the word 'balloon' based on the minimum occurrences of its characters. This is efficient and straightforward.
⚙️
Algorithm
3 steps- 1Step 1: Count the frequency of each character in the input string.
- 2Step 2: For the characters in 'balloon', calculate how many complete sets can be formed based on their counts.
- 3Step 3: Return the minimum number of complete sets that can be formed.
solution.py9 lines
1# Full working Python code
2from collections import Counter
3
4def maxBalloons(text):
5 count = Counter(text)
6 return min(count['b'], count['a'], count['l'] // 2, count['o'] // 2, count['n'])
7
8# Example usage
9print(maxBalloons('loonbalxballpoon')) # Output: 2ℹ
Complexity note: The time complexity is O(n) because we only need to iterate through the string once to count the characters. The space complexity is O(n) due to the storage of character counts.
- 1The word 'balloon' requires specific counts of certain letters.
- 2The letters 'l' and 'o' are needed twice, which affects the total count.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.