You have a string text of lower-case letters, like tiles in a word game. You want to spell the word "balloon" with these tiles as many times as you can.
Each tile can be used in only one word. Return how many full copies of "balloon" you can spell.
Example 1
Input: text = "baollnob" Output: 1 Why: one a and one n, so only one word; the spare b is wasted
2 more examples and the constraints
Example 2
Input: text = "noolbaxnoolabllz" Output: 2 Why: two of b, a, n and four of l and o
Example 3
Input: text = "bloom" Output: 0 Why: there is no a and no n
Constraints
- 1 ≤ length of text ≤ 10,000
- text contains only lower-case English letters
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Cross out lettersO(n²)
- Count and divideO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 10,000 letters | Verdict |
|---|---|---|---|
| Cross out letters | O(n²) | Mention it, then move on | |
| Count and divide | O(n) | Best; one pass |
n = length of text.
Edge cases to test
- Double letters. "balon" has one of everything but needs two l and two o: the answer is 0.
- A missing letter. "bloom" has no a, so nothing can be spelled.
- Extra letters. Letters outside balloon, like x and z, change nothing.
- Odd l or o count. Three l tiles only cover one word; integer division drops the spare.
Common mistakes
- Forgetting that l and o are needed twice, so their counts are not halved.
- Rounding the halved counts up instead of down.
- Taking the minimum over every letter in the text instead of only the five letters of balloon.
How to talk through it
- 1Clarify. Can each letter be used only once? Is the text only lower-case letters?
- 2Drop the order. Spelling a word only needs the right number of each letter, so count them.
- 3Divide by the need. Each letter allows count ÷ need words; the l and o need is 2.
- 4Take the minimum. The scarcest letter caps the answer. O(n) time, O(1) space.
- 5Test out loud. Run "balon", "bloom" and a case with three l tiles.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?