Problem Description
Given a string text, determine the maximum number of times the word "balloon" can be formed using the characters in text. Each character in text can be used at most once.
Key Insights
- Count the frequency of each character in the text.
- The target word "balloon" requires:
- b: 1
- a: 1
- l: 2
- o: 2
- n: 1
- The number of times "balloon" can be formed is limited by the minimum value among these frequencies (taking into account that l and o are needed twice).
Space and Time Complexity
Time Complexity: O(n), where n is the length of text. Space Complexity: O(1), as the frequency count uses constant space (only lower-case English letters).
Solution
We first build a frequency map of characters in the input text using a hash table (or dictionary). For the word "balloon", we calculate the possible counts by taking:
- The count of 'b'
- The count of 'a'
- The count of 'n'
- The count of 'l' divided by 2 (since two are needed)
- The count of 'o' divided by 2 (since two are needed)
The answer is the minimum of all these values, ensuring that all necessary characters are available in the required quantities. This approach is efficient due to single-pass counting and constant extra space.