Given a string text, how many times can you form the word "balloon" using each character at most once? For text = "loonbalxballpoon" the answer is 2.
from collections import Counter
def max_number_of_balloons(text):
have = Counter(text)
need = Counter("balloon") # b:1 a:1 l:2 o:2 n:1
return min(have[c] // k for c, k in need.items())
Each copy of "balloon" needs one b, one a, two l, two o and one n. The number of full copies is limited by whichever letter runs out first, so take the minimum of have // need across those five letters. O(n) time, O(1) space (fixed alphabet).
need from the word itself avoids hard-coding mistakes.Counter returns 0 for absent keys, so a text with no "b" correctly yields 0 without special cases.This "resource bottleneck" pattern also shows up in Ransom Note (383) and Rearrange Characters to Make Target String (2287).
For live practice on explaining patterns like this, try Linkjob.ai, an AI interview assistant. (Disclosure: I work on Linkjob AI.)