#3541

Find Most Frequent Vowel and Consonant

Easy
Hash TableStringCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Use a single pass to count frequencies in a hash map, allowing efficient retrieval of max frequencies.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a frequency map for vowels and consonants.
  2. 2Step 2: Traverse the string once, updating the frequency map based on character type.
  3. 3Step 3: Calculate the maximum frequency for vowels and consonants and return their sum.
solution.py10 lines
1def most_frequent(s):
2    freq = {'vowels': {}, 'consonants': {}}
3    for char in s:
4        if char in 'aeiou':
5            freq['vowels'][char] = freq['vowels'].get(char, 0) + 1
6        else:
7            freq['consonants'][char] = freq['consonants'].get(char, 0) + 1
8    max_vowel = max(freq['vowels'].values(), default=0)
9    max_consonant = max(freq['consonants'].values(), default=0)
10    return max_vowel + max_consonant

Complexity note: The algorithm processes the string in a single pass, leading to O(n) complexity.

  • 1Vowels and consonants can be counted separately.
  • 2Using a hash map allows for efficient frequency counting.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.