Description

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 <= 104
  • text consists of lower case English letters only.

Follow up: Note: This question is the same as 2287. Rearrange Characters to Make Target String.

💡 Hint 1:
Count the frequency of letters in the given string.

💡 Hint 2:
Find the letter than can make the minimum number of instances of the word "balloon".

Submitted Code

class Solution:
    def maxNumberOfBalloons(self, text: str) -> int:
        letter_count = {'b': 0, 'a': 0, 'n': 0, 'l': 0, 'o': 0}
    
        for c in text:
            if c in letter_count:
                letter_count[c] += 1
        
        letter_count['l'] //= 2
        letter_count['o'] //= 2

        return min(letter_count.values())

Runtime: 0 ms | Beats 100.00%
Memory: 17.25 MB | Beats 91.07%

문자 b, a, n, l, o가 키로 들어있는 해시 테이블을 미리 생성하는 방법이 가장 빨랐다.

Other Solutions

1st

class Solution:
    def maxNumberOfBalloons(self, text: str) -> int:
        m = {c: text.count(c) for c in text}
        return min(m.get('b', 0), m.get('a', 0), m.get('l', 0)//2, m.get('o', 0)//2, m.get('n', 0))

time complexity: 𝑂(𝑛)
space complexity: 𝑂(1)

2nd

class Solution:
    def maxNumberOfBalloons(self, text):
        cnt = Counter(text)
        return min(cnt["b"], cnt["a"], cnt["l"]//2, cnt["o"]//2, cnt["n"])

Leave a comment