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.
1#include <iostream>
2#include <unordered_map>
3using namespace std;
4
5int maxNumberOfBalloons(string text) {
6 unordered_map<char, int> count;
7 for (char c : text)
8 count[c]++;
9 count['l'] /= 2;
10 count['o'] /= 2;
11 return min({count['b'], count['a'], count['l'], count['o'], count['n']});
12}
13
14int main() {
15 cout << maxNumberOfBalloons("loonbalxballpoon") << endl;
16 return 0;
17}
The C++ solution utilizes an unordered_map to count the characters in the input string. Similar to the C code, it adjusts counts for 'l' and 'o' and calculates the minimum frequency among the needed 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.
The Python solution uses individual variables to maintain character counts for 'b', 'a', 'l', 'o', and 'n'. It divides the 'l' and 'o' counts by 2 to adjust double usage and then calculates the minimum possible count of full 'balloon' sets.