Sponsored
Sponsored
This approach involves counting the frequency of each character in the string 'text' and then determining how many full instances of the word 'balloon' can be formed based on these frequencies. We will count the occurrences of the characters 'b', 'a', 'l', 'o', and 'n'. Since 'l' and 'o' appear twice in the word 'balloon', their counts should be halved. Finally, we find the minimum number of complete 'balloon' words that can be formed using these character counts.
Time Complexity: O(n), where n is the length of the input string.
Space Complexity: O(1), since we are using a constant amount of extra space.
1from collections import Counter
2
3def maxNumberOfBalloons(text: str) -> int:
4 count = Counter(text)
5 count['l'] //= 2
6 count['o'] //= 2
7 return min(count[c] for c in 'balon')
8
9print(maxNumberOfBalloons("loonbalxballpoon"))
The Python solution uses the Counter class to count character frequencies. After adjusting counts for 'l' and 'o', it finds the minimum frequency among the required characters to determine the number of 'balloon' instances.
Instead of counting characters explicitly, this approach calculates the maximum number of 'balloon' instances by directly comparing the ratios of character counts required. Specifically, for 'b', 'a', and 'n', the ratio is 1:1, but for 'l' and 'o', the ratio is 1:2 in 'balloon'. This approach simplifies checking character sufficiency by calculating the feasible number of 'balloon' words based on the complete sets of these character combinations.
Time Complexity: O(n), where n is the length of the input string.
Space Complexity: O(1), as it uses a fixed number of variables for counting.
This JavaScript solution uses separate count variables for each character involved in forming 'balloon'. It optimize counts of 'l' and 'o' by dividing by 2 and checks for maximum sets that can be formed using the calculated minimum.