Problem statement:
Given a string text
, find the maximum number of possible instances of the word "balloon" using the characters of given text. Each character in text is used at most once.
Example 1:
Input: text = "lenobxlao"
Output: 1
Example 2:
Input: text = "lollbcolatnaboon"
Output: 2
Algorithmic Steps This problem is solved with the help of map(or object) data structure to store the character count. The algorithmic approach can be summarized as follows:
-
Initialize a balloon object(
balloonObj
) to store the number of occurances of each character in "balloon" word. -
Define a character occurances of given text(
text
) incountTextObj
variable. -
Iterate over characters of given text and update
countTextObj
with it's character occurances. The character count is calculated only for the characters which present in "balloon" word. -
Define a
minBalloons
variable, initialized to infinity. -
Iterate over characters of balloon word, calculate the possible number of balloon words based on given text.
-
Return
minBalloons
indicating the possible maximum number of balloon words.
Time and Space complexity:
This algorithm has a time complexity of O(n)
, Where n
is the length of the input string (text
). This is because we traverse the string once to count characters and then iterate over the fixed size(5 characters) of the balloonObj
.
Here, it takes constant time complexity of O(1)
. This is because the size of balloonObj
is constant and doesn't scale with input size. Eventhough countTextObj
grows based on number of characters in text
, its size is capped by the distinct characters of "balloon" word.