Maximum Number of Balloons Problem
Description
LeetCode Problem 1189.
Given a string text, you want to use the characters of text to form as many instances of the word "balloon" as possible.
You can use each character in text at most once. Return the maximum number of instances that can be formed.
Example 1:
Input: text = "nlaebolko"
Output: 1
Example 2:
Input: text = "loonbalxballpoon"
Output: 2
Example 3:
Input: text = "leetcode"
Output: 0
Constraints:
1 <= text.length <= 10^4textconsists of lower case English letters only.
Note: This question is the same as 2287: Rearrange Characters to Make Target String.
Solution
Approach: Count the Letters
Each copy of "balloon" uses one b, one a, two l, two o and one n. Count how many times each letter appears in text. The number of copies is then limited by the scarcest letter, taking into account that l and o are needed twice:
min(count[b], count[a], count[l] / 2, count[o] / 2, count[n]), with the divisions rounded down.
For example, "loonbalxballpoon" has 2 b, 2 a, 4 l, 4 o and 2 n, so every limit is 2 and the answer is 2. A letter that does not occur at all gives 0.
Complexity: O(n) time and O(1) extra space for the 26 counters.
class Solution:
def maxNumberOfBalloons(self, text: str) -> int:
count = {}
for ch in text:
count[ch] = count.get(ch, 0) + 1
# "balloon" needs one b, a and n, and two l and o.
return min(count.get("b", 0), count.get("a", 0), count.get("l", 0) // 2,
count.get("o", 0) // 2, count.get("n", 0))