AlgoMaster Logo

Maximum Number of Balloons

Ashish

Ashish Pratap Singh

easy

Problem Description

Solve it on LeetCode

Approaches

1. Frequency Count with Maps

Intuition:

  • The word "balloon" consists of the letters: 'b', 'a', 'l', 'o', 'n'.
  • We need to count these letters in the input string and determine how many times we can form the word "balloon".
  • For 'l' and 'o', we need the count divided by 2 because these letters appear twice in "balloon".

Steps:

  1. Create a frequency map for the characters in the input string.
  2. Check the count of each character needed for "balloon".
  3. The count of possible "balloons" that can be formed is determined by the minimum ratio of available to needed instances of these characters.

Code:

2. Optimized Frequency Count with Arrays

Intuition:

This approach builds on the idea of counting character frequencies, but instead of using a map or dictionary, which carries extra overhead, we use a fixed-size array of length 26.

Since the problem only involves lowercase English letters, each character 'a' to 'z' can be mapped directly to an array index (c - 'a'), making both counting and lookups extremely fast.

Once we know how many times each required character appears in the input string, we compute how many full occurrences of the word "balloon" can be formed.

Steps:

  1. Create an integer array of size 26 to store the frequency of each lowercase letter.
  2. Count the characters in the input string by incrementing the corresponding index in the array.
  3. For each character in the word "balloon" (b, a, l, l, o, o, n), compute how many times it can contribute to forming the word.
    • For 'l' and 'o', divide counts by 2 because each appears twice.
  4. The answer is the minimum among these available counts.

Code:

Example Walkthrough:

Imagine counting characters in "loonbalxballpoon":

To form "balloon":

The limiting character is 'a', so the maximum balloons = 1.