Leetcode Problem 1189: Maximum Number of Balloons
Given a string text
, you want to use the characters of text
to form as many instances of the word “balloon” as possible. Each character in the string text
can only be used once. Return the maximum number of instances that can be formed.
text
guaranteed to be alphabetic or could there be other types of characters?
def maxNumberOfBalloons(text: str) -> int:
from collections import Counter
# Count all characters in the input text
count = Counter(text)
# The word we need to form is "balloon"
balloon_count = Counter("balloon")
# Find the minimum number of times we can form "balloon"
return min(count[char] // balloon_count[char] for char in balloon_count)
# Example usage
print(maxNumberOfBalloons("nlaebolko")) # Output should be 1
print(maxNumberOfBalloons("loonbalxballpoon")) # Output should be 2
print(maxNumberOfBalloons("leetcode")) # Output should be 0
collections.Counter
to count the frequency of each character in the input string text
.Compute Instances: For each character in the word “balloon”, determine how many times it can be used (i.e., text_count[char] // balloon_count[char]
).
n
is the length of the input string text
.This solution should be efficient even for the upper limits of typical input sizes in interview scenarios.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?