Maximum Number of Balloons

easy hash table string counting

Problem

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.

Inputtext = "loonbalxballpoon"
Output2
The letters allow exactly two copies of "balloon"; both 'l' and 'o' are needed twice per word.

def max_number_of_balloons(text):
    counts = {}
    for ch in text:
        counts[ch] = counts.get(ch, 0) + 1
    need = {"b": 1, "a": 1, "l": 2, "o": 2, "n": 1}
    best = float("inf")
    for ch, k in need.items():
        best = min(best, counts.get(ch, 0) // k)
    return best
function maxNumberOfBalloons(text) {
  const counts = {};
  for (const ch of text) counts[ch] = (counts[ch] || 0) + 1;
  const need = { b: 1, a: 1, l: 2, o: 2, n: 1 };
  let best = Infinity;
  for (const ch in need) {
    best = Math.min(best, Math.floor((counts[ch] || 0) / need[ch]));
  }
  return best;
}
class Solution {
    public int maxNumberOfBalloons(String text) {
        int[] counts = new int[26];
        for (char ch : text.toCharArray()) counts[ch - 'a']++;
        int best = Integer.MAX_VALUE;
        best = Math.min(best, counts['b' - 'a']);
        best = Math.min(best, counts['a' - 'a']);
        best = Math.min(best, counts['l' - 'a'] / 2);
        best = Math.min(best, counts['o' - 'a'] / 2);
        best = Math.min(best, counts['n' - 'a']);
        return best;
    }
}
int maxNumberOfBalloons(string text) {
    int counts[26] = {0};
    for (char ch : text) counts[ch - 'a']++;
    int best = INT_MAX;
    best = min(best, counts['b' - 'a']);
    best = min(best, counts['a' - 'a']);
    best = min(best, counts['l' - 'a'] / 2);
    best = min(best, counts['o' - 'a'] / 2);
    best = min(best, counts['n' - 'a']);
    return best;
}
Time: O(n) Space: O(1)