Maximum Number of Balloons
💻 coding

Maximum Number of Balloons

1 min read 210 words
1 min read
ShareWhatsAppPost on X
  • 1The task is to determine how many times the word 'balloon' can be formed from the characters in a given string.
  • 2Characters can only be used once, and specific letters must appear in certain quantities to form the word.
  • 3The solution involves counting character occurrences and adjusting for letters that appear multiple times in 'balloon'.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The task is to determine how many times the word 'balloon' can be formed from the characters in a given string."

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.

Example 1:

Input: text = "nlaebolko"

Output: 1

Example 2:

Input: text = "loonbalxballpoon"

Output: 2

Example 3:

Input: text = "leetcode"

Output: 0

Constraints:

1 <= text.length <= 10^4

text consists of lower case English letters only.

Solution:

using System;
using System.Collections.Generic;
using System.Text;

namespace LeetCode.AskGif.Easy.String
{
 class MaxNumberOfBalloonsSln
 {
 public void execute()
 {
 var res = MaxNumberOfBalloons("leetcode");
 }

 public int MaxNumberOfBalloons(string text)
 {
 var dict = new Dictionary<char, int>();
 char[] word = new char[] {'b', 'a', 'l', 'l', 'o', 'o', 'n' };
 foreach (var ch in text)
 {
 if(dict.ContainsKey(ch))
 {
 dict[ch]++;
 }
 else
 {
 dict[ch] = 1;
 }
 }

 int min = Int16.MaxValue;

 //since l and o appear twice, lets divide it by two in dictionary if they exists
 if(dict.ContainsKey('l'))
 dict['l'] = dict['l'] / 2;
 if (dict.ContainsKey('o'))
 dict['o'] = dict['o'] / 2;

 foreach (var ch in word)
 {
 if (dict.ContainsKey(ch))
 {
 if(dict[ch]<min)
 {
 min = dict[ch];
 }
 }
 else
 {
 return 0;
 }
 }

 return min;
 }
 }
}

Time Complexity: O(n)

Space Complexity: O(n)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 3 May 2020 · 1 min read · 210 words

Part of AskGif Blog · coding

You might also like