Maximum Number of Balloons
Problem
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).text = "loonbalxballoon"Output2text = "abnoollb"Output1text = "bonsai"Output01 ≤ text.length ≤ 104 · text has lowercase English letters only
Try it yourself
class Solution {
public int maxNumberOfBalloons(String text) {
}
}
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.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
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.
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.
OptimalCount Letters, Take the Bottleneck
O(n)Space O(1)Tally all 26 letters in one pass. Copies are limited by
b, a, n, l/2 and
o/2 (integer division); the minimum of those five numbers is how many
full words fit.
public int maxNumberOfBalloons(String text) { int[] freq = new int[26]; for (int i = 0; i < text.length(); i++) freq[text.charAt(i) - 'a']++; int ans = Math.min(freq['b' - 'a'], freq['a' - 'a']); ans = Math.min(ans, freq['n' - 'a']); ans = Math.min(ans, freq['l' - 'a'] / 2); // two l's per word ans = Math.min(ans, freq['o' - 'a'] / 2); // two o's per word return ans; }
Dry runtext = "loonbalxballoon"
- countb:2a:2l:4o:4n:2tally the text
- halveb:2a:2l:2o:2n:2l, o needed twice
- minb:2ma:2l:2o:2n:2min = 2 ✔
One linear pass and a fixed 26-slot array — nothing left to improve.
have[c] / need[c].At a glance
| Level | Approach | Time | Space |
|---|---|---|---|
| Brute Force | Spell Words One by One | O(n2) | O(n) |
| Optimal | Count Letters, Take the Bottleneck | O(n) | O(1) |
- Forgetting that
landoare 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.
- Phrase it as a bottleneck: the scarcest required letter decides the answer.
- Offer the general
have / needversion for an arbitrary target word. - Point out the array of 26 makes the extra space O(1).