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.
1using System;
2using System.Linq;
3
4public class Solution {
5 public int MaxNumberOfBalloons(string text) {
6 var count = new int[26];
7 foreach (char c in text)
8 count[c - 'a']++;
9 count['l' - 'a'] /= 2;
10 count['o' - 'a'] /= 2;
11 return new [] {count['b' - 'a'], count['a' - 'a'], count['l' - 'a'], count['o' - 'a'], count['n' - 'a']}.Min();
12 }
13
14 public static void Main() {
15 var solution = new Solution();
16 Console.WriteLine(solution.MaxNumberOfBalloons("loonbalxballpoon"));
17 }
18}
The C# solution uses an array to store frequency counts for each character in the string. It adjusts counts for 'l' and 'o' and finds the minimum count of required characters to calculate the maximum number of 'balloon' words that 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.