Count the five required letters and take the minimum available copies, halving the counts for the two letters used twice.
Complexity
O(n) time and O(1) space.
Count how many copies of the word balloon can be formed from a text's letters.
Count the five required letters and take the minimum available copies, halving the counts for the two letters used twice.
O(n) time and O(1) space.
package main
func maxNumberOfBalloons(text string) int {
count := map[rune]int{}
for _, character := range text {
count[character]++
}
values := []int{count['b'], count['a'], count['l'] / 2, count['o'] / 2, count['n']}
answer := values[0]
for _, value := range values[1:] {
if value < answer {
answer = value
}
}
return answer
}
from collections import Counter
class Solution:
def maxNumberOfBalloons(self, text: str) -> int:
count = Counter(text)
return min(count["b"], count["a"], count["l"] // 2, count["o"] // 2, count["n"])
function maxNumberOfBalloons(text: string): number {
const count = new Map<string, number>(); for (const character of text) count.set(character, (count.get(character) ?? 0) + 1);
return Math.min(count.get("b") ?? 0, count.get("a") ?? 0, Math.floor((count.get("l") ?? 0) / 2), Math.floor((count.get("o") ?? 0) / 2), count.get("n") ?? 0);
}