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.
1function maxNumberOfBalloons(text) {
2 const count = {};
3 for (const char of text) {
4 count[char] = (count[char] || 0) + 1;
5 }
6 count['l'] = Math.floor((count['l'] || 0) / 2);
7 count['o'] = Math.floor((count['o'] || 0) / 2);
8 const minCount = Math.min(count['b'] || 0, count['a'] || 0, count['l'] || 0, count['o'] || 0, count['n'] || 0);
9 return minCount;
10}
11
12console.log(maxNumberOfBalloons("loonbalxballpoon"));
The JavaScript solution uses an object to keep track of the frequency of each character in the input string. It adjusts the counts for 'l' and 'o' and calculates the minimum frequency needed to form the maximum 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.