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 <stdio.h>
2#include <string.h>
3
4int maxNumberOfBalloons(char* text) {
5 int count[26] = {0};
6 for (int i = 0; text[i]; i++)
7 count[text[i] - 'a']++;
8 count['l' - 'a'] /= 2;
9 count['o' - 'a'] /= 2;
10 int min = count['b' - 'a'];
11 min = min < count['a' - 'a'] ? min : count['a' - 'a'];
12 min = min < count['l' - 'a'] ? min : count['l' - 'a'];
13 min = min < count['o' - 'a'] ? min : count['o' - 'a'];
14 min = min < count['n' - 'a'] ? min : count['n' - 'a'];
15 return min;
16}
17
18int main() {
19 char text[] = "loonbalxballpoon";
20 printf("%d\n", maxNumberOfBalloons(text));
21 return 0;
22}
The C solution uses an array of size 26 to store the frequency of each letter in the input string 'text'. The count for 'l' and 'o' is divided by two because they appear twice in 'balloon'. Finally, it calculates the minimum count required among 'b', 'a', 'l', 'o', and 'n' to determine how many instances of 'balloon' can be formed.
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.