You are given a string text, you want to use the characters of text to form as many instances of the word "balloon" as possible.
You can use each character in text at most once. Return the maximum number of instances that can be formed.
Example 1:
Input: text = "nlaebolko"
Output: 1Example 2:
Input: text = "loonbalxballpoon"
Output: 2Example 3:
Input: text = "neetcode"
Output: 0Constraints:
1 <= text.length <= 10,000text consists of lower case English letters only.Before attempting this problem, you should be comfortable with:
To form the word "balloon", we need specific counts of each letter: one each of 'b', 'a', 'n', and two each of 'l' and 'o'. The number of times we can spell "balloon" is limited by whichever required letter runs out first. By counting all letters in the text and then dividing by the required amounts, we find how many complete words we can form.
We can optimize by only counting the five relevant characters ('b', 'a', 'l', 'o', 'n') instead of all 26 letters. After counting, we adjust for 'l' and 'o' by dividing their counts by 2 since each "balloon" requires two of each. The minimum count then gives our answer directly.
0 (cannot form even one "balloon").'l' and 'o' by 2 to account for needing two of each.The word "balloon" contains two ls and two os. A common mistake is treating all characters equally without dividing the counts of l and o by 2. This results in overcounting the number of possible words that can be formed.
If any of the five required characters (b, a, l, o, n) is missing from the text, the answer is 0. Failing to handle this case (for example, by taking the minimum of an empty collection or dividing by zero) can cause runtime errors or incorrect results.