Find Most Frequent Vowel and Consonant (LeetCode 3541): Solution and Explanation

Easy
Hash Table
String
Counting

Given a lowercase string, find the highest count of any single vowel and the highest count of any single consonant, and return their sum. A group that does not appear contributes 0.

Intuition

The answer only depends on how often each letter appears, not where. So the first job is a frequency table of the 26 letters.

Once the counts are known, the letters split into two shelves: five vowels and 21 consonants. The answer is the tallest bucket on each shelf added together.

Approach: Count, then take one maximum per group

  1. Build cnt[26] by adding 1 for each character of s.
  2. Set vowel = consonant = 0.
  3. For each letter, update vowel if it is one of a, e, i, o, u, otherwise update consonant, keeping the larger count.
  4. Return vowel + consonant.

Step-by-step example

s = "successes"
  1. Counting gives s = 4, u = 1, c = 2, e = 2.
  2. Vowel shelf: 'e' has 2 and 'u' has 1, so vowel = 2.
  3. Consonant shelf: 'c' has 2 and 's' has 4, so consonant = 4.
  4. Return 2 + 4 = 6.

Code: Python, Java, C++

1class Solution:
2    def maxFreqSum(self, s: str) -> int:
3        cnt = [0] * 26
4        for ch in s:
5            cnt[ord(ch) - ord('a')] += 1
6        vowel = consonant = 0
7        for i in range(26):
8            if chr(i + 97) in 'aeiou':
9                vowel = max(vowel, cnt[i])
10            else:
11                consonant = max(consonant, cnt[i])
12        return vowel + consonant
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

One pass counts the characters, then a fixed 26-step scan finds both maxima.

Space

O(1)

The count table always has 26 entries, no matter how long the string is.

Other approaches

Hash map counter (time O(n), space O(1))

Use a dictionary or Counter instead of an array, then take the max over vowel keys and over consonant keys. Same idea, a little more overhead.

Update maxima while counting (time O(n), space O(1))

Raise the matching maximum right after each increment. This merges the two loops into one, since counts only grow.

Common mistakes

  • Adding up all vowel counts instead of taking the single most frequent vowel.
  • Treating 'y' as a vowel. Here only a, e, i, o and u are vowels.
  • Crashing on max() of an empty group, for example a string with no vowels. Start both maxima at 0.

Frequently asked questions

What if two vowels tie for the top count?

It does not matter which one you pick, because only the count is returned and both have the same count.

What is returned for a string of only consonants?

The vowel part is 0, so the answer is just the count of the most frequent consonant. "rhythm" gives 0 + 2 = 2 because 'h' appears twice.

Why is this O(1) space?

The table is sized by the alphabet, which is fixed at 26 letters, not by the input length.