Leetcode 1189. Maximum Number of Balloons
Given a string text
, you want to use the characters of text
to form as many instances of the word “balloon” as possible. You can use each character in text
at most once. Return the maximum number of instances that can be formed.
text
?
1 <= text.length <= 10^4
.text
.Therefore, we need:
Form Instances: Determine the limiting factor by calculating how many times we can extract “balloon” from our character counts. For each required character, calculate how many times it can contribute to forming “balloon”.
import java.util.HashMap;
import java.util.Map;
public class Solution {
public int maxNumberOfBalloons(String text) {
Map<Character, Integer> charCount = new HashMap<>();
// Count frequency of each character in text
for (char c : text.toCharArray()) {
charCount.put(c, charCount.getOrDefault(c, 0) + 1);
}
// Required frequency for each character in "balloon"
int bCount = charCount.getOrDefault('b', 0);
int aCount = charCount.getOrDefault('a', 0);
int lCount = charCount.getOrDefault('l', 0);
int oCount = charCount.getOrDefault('o', 0);
int nCount = charCount.getOrDefault('n', 0);
// Calculate the maximum number of "balloon" instances
int maxBalloons = Integer.MAX_VALUE;
maxBalloons = Math.min(maxBalloons, bCount);
maxBalloons = Math.min(maxBalloons, aCount);
maxBalloons = Math.min(maxBalloons, lCount / 2);
maxBalloons = Math.min(maxBalloons, oCount / 2);
maxBalloons = Math.min(maxBalloons, nCount);
return maxBalloons;
}
}
text
, giving a time complexity of (O(n)) where (n) is the length of the string.Thus, the overall time complexity is (O(n)), which is efficient for the given constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?