Maximum Number of Balloons

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.

LeetCode Problem - 1189

class Solution {
    public int maxNumberOfBalloons(String text) {
        // Define the target word "balloon"
        String target = "balloon";

        // Create a map to store the frequency of characters in the input text
        Map<Character, Integer> map1 = new HashMap<>();
        for (char ch : text.toCharArray()) {
            map1.put(ch, map1.getOrDefault(ch, 0) + 1); // Increment the count for each character in text
        }

        // Create a map to store the frequency of characters in the target word "balloon"
        Map<Character, Integer> map2 = new HashMap<>();
        for (char ch : target.toCharArray()) {
            map2.put(ch, map2.getOrDefault(ch, 0) + 1); // Increment the count for each character in "balloon"
        }

        // Initialize the minimum value to represent the maximum number of times "balloon" can be formed
        int min = Integer.MAX_VALUE;

        // Iterate through each character in the target string "balloon"
        for (char ch : target.toCharArray()) {
            try {
                // Get the frequency of the character from the input text and the target word
                int val1 = map1.get(ch);   // Frequency of ch in text
                int val2 = map2.get(ch);   // Frequency of ch in "balloon"

                // Calculate the maximum number of times the character can contribute to forming the target word
                min = Math.min(min, val1 / val2);
            } catch (Exception e) {
                // If a character from "balloon" is not found in text, return 0 as the target can't be formed
                return 0;
            }
        }

        // Return the minimum number of times the word "balloon" can be formed
        return min;
    }
}

Did you find this article valuable?

Support Perf Insights by becoming a sponsor. Any amount is appreciated!