Maximum Number of Balloons

EasyHashing · Frequency Counting🧩 Hashing & CountingLeetCode #1189 ↗Updated

Problem

Each character of the lowercase string text may be used at most once. Return how many complete copies of the word "balloon" you can spell with its characters (order does not matter).
Inputtext = "loonbalxballoon"Output2
Inputtext = "abnoollb"Output1
Inputtext = "bonsai"Output0

1 ≤ text.length ≤ 104  ·  text has lowercase English letters only

Try it yourself

Java
class Solution {
    public int maxNumberOfBalloons(String text) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Each copy needs one b, a, n and two l and o. Count the letters once; the scarcest one after dividing l and o by 2 is the bottleneck — that is the answer.
PatternHashing & Counting

Instinct Need "have I seen this before?", "how many times?" or "group things that look alike"? Trade memory for O(1) lookups with a HashMap, HashSet or int[26].

Memory hack Don't search, remember - every element checks in at the front desk, and the desk answers instantly.

Open the Hashing & Counting guide →

Approaches

Brute ForceSpell Words One by One

Time O(n2)Space O(n)

Copy the text into a mutable buffer and keep trying to spell one more "balloon": for each of its 7 letters, find and delete one occurrence. The first letter that cannot be found means no further copy is possible.

Java
public int maxNumberOfBalloons(String text) {
    StringBuilder pool = new StringBuilder(text);
    int count = 0;
    while (true) {
        for (char ch : "balloon".toCharArray()) {
            int idx = pool.indexOf(String.valueOf(ch));
            if (idx < 0) return count; // missing letter: no more full words
            pool.deleteCharAt(idx);    // consume it
        }
        count++;
    }
}

Directly models “use each letter once”, but each round rescans the text.

At a glance

LevelApproachTimeSpace
Brute ForceSpell Words One by OneO(n2)O(n)
OptimalCount Letters, Take the BottleneckO(n)O(1)
Common pitfalls
  • Forgetting that l and o are needed twice per word.
  • Taking the min over all 26 letters — letters not in the word must be ignored.
  • Counting only the letters of the word, then dividing every count by 2.
Interview tips
  • Phrase it as a bottleneck: the scarcest required letter decides the answer.
  • Offer the general have / need version for an arbitrary target word.
  • Point out the array of 26 makes the extra space O(1).
Pattern
Frequency counting → “how many times can I build X from these pieces” becomes a min over count ratios.
My notes saved in this browser