Facebook Pixel

3541. Find Most Frequent Vowel and Consonant

Problem Description

You are given a string s consisting of lowercase English letters ('a' to 'z').

Your task is to:

  1. Find the vowel (one of 'a', 'e', 'i', 'o', or 'u') with the maximum frequency.
  2. Find the consonant (all other letters excluding vowels) with the maximum frequency.

Return the sum of the two frequencies.

Note: If multiple vowels or consonants have the same maximum frequency, you may choose any one of them. If there are no vowels or no consonants in the string, consider their frequency as 0.

The frequency of a letter x is the number of times it occurs in the string.

Intuition

To solve the problem, we need to determine the highest frequency of vowels and consonants in the given string s. This can be efficiently accomplished using a counting method:

  1. Counting Frequencies: Utilize a hash table (or a dictionary) to count how many times each character appears in the string s. This allows us to quickly access the frequency of any particular letter.

  2. Identify Maximum Frequencies:

    • Initialize two variables, a for the maximum frequency of vowels and b for the maximum frequency of consonants.
    • Traverse the counted frequencies: for each character, check if it is a vowel or a consonant. If it's a vowel, update a with the maximum value between the current value of a and the character's frequency. If it's a consonant, update b similarly.
  3. Return the Result: The solution is then simply the sum of a and b, representing the sum of the highest frequencies of vowels and consonants across the string.

By systematically counting and comparing frequencies, we ensure that our solution is efficient and direct.

Solution Approach

To implement the solution, we use a counting approach as described in the Reference Solution Approach:

  1. Data Structure - Counter: We utilize Python's Counter from the collections module, which helps in efficiently counting the frequency of each character in the given string s.

  2. Algorithm:

    • Initialize a and b to zero. These variables will track the maximum frequency of any vowel and consonant, respectively.
    • Iterate over the items in cnt, which represents the character frequencies of s.
    • For each character-frequency pair (c, v), check if c is a vowel by verifying if it is in the string "aeiou".
      • If it is a vowel, update a using a = max(a, v).
      • Else, treat it as a consonant and update b using b = max(b, v).
    • Finally, return the sum a + b, which provides the combined maximum frequencies of the most frequent vowel and consonant.

This method effectively leverages counting, separate tracking of vowel and consonant frequencies, and the use of conditional logic to dynamically determine the maximum frequencies.

Here's the code implementing this approach:

from collections import Counter

class Solution:
    def maxFreqSum(self, s: str) -> int:
        cnt = Counter(s)
        a = b = 0
        for c, v in cnt.items():
            if c in "aeiou":
                a = max(a, v)
            else:
                b = max(b, v)
        return a + b

This solution is efficient, with the counting process executed in O(n) time complexity, where n is the length of the string s. The traversal of constant-sized alphabets ensures that the approach remains effective for varying input sizes.

Ready to land your dream job?

Unlock your dream job with a 2-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's walk through an example to illustrate the solution approach using the provided problem description and solution.

Example:

Consider the string s = "programming". We want to find the highest frequency of a vowel and a consonant and then sum these frequencies.

  1. Counting Frequencies:

    • Use Counter from Python's collections module to count the frequency of each character in the string s.
    • The character frequencies for "programming" are:
      • 'p': 1
      • 'r': 2
      • 'o': 1
      • 'g': 2
      • 'a': 1
      • 'm': 2
      • 'i': 1
      • 'n': 1
  2. Identify Maximum Frequencies:

    • Initialize a and b to zero, representing the maximum frequency of a vowel and a consonant, respectively.
    • Iterate through the characters and their frequencies:
      • For the character 'o' (vowel), update a = max(0, 1), resulting in a = 1.
      • For the character 'a' (vowel), update a = max(1, 1), a remains 1.
      • For the character 'i' (vowel), update a = max(1, 1), a remains 1.
      • For all other consonants, determine the highest frequency:
        • 'r': a = max(0, 2), b = 2
        • 'g': a = max(2, 2), b remains 2
        • 'm': a = max(2, 2), b remains 2
    • After iterating, the maximum frequency for vowels is 1 and for consonants it is 2.
  3. Return the Result:

    • Sum the maximum frequencies: a + b = 1 + 2 = 3.
    • Therefore, the result for the string "programming" is 3.

Solution Implementation

1from collections import Counter
2
3class Solution:
4    def maxFreqSum(self, s: str) -> int:
5        # Count the frequency of each character in the string 's'
6        frequency_counter = Counter(s)
7      
8        # Initialize maximum frequency variables for vowels and consonants
9        max_vowel_frequency = 0
10        max_consonant_frequency = 0
11      
12        # Iterate through the counted frequencies
13        for char, frequency in frequency_counter.items():
14            # Check if the character is a vowel
15            if char in "aeiou":
16                # Update maximum vowel frequency if the current frequency is greater
17                max_vowel_frequency = max(max_vowel_frequency, frequency)
18            else:
19                # Otherwise, update maximum consonant frequency if the current frequency is greater
20                max_consonant_frequency = max(max_consonant_frequency, frequency)
21      
22        # Return the sum of the highest frequency of vowels and consonants
23        return max_vowel_frequency + max_consonant_frequency
24
1class Solution {
2    public int maxFreqSum(String s) {
3        // Array to count the frequency of each letter
4        int[] frequency = new int[26];
5      
6        // Count the frequency of each character in the string
7        for (char character : s.toCharArray()) {
8            frequency[character - 'a']++;
9        }
10      
11        // Variables to store maximum frequency of vowels and consonants
12        int maxVowelFreq = 0;
13        int maxConsonantFreq = 0;
14      
15        // Iterate over the frequency array to find the maximum frequency for vowels and consonants
16        for (int i = 0; i < frequency.length; i++) {
17            char currentChar = (char) (i + 'a');
18            if (isVowel(currentChar)) {
19                maxVowelFreq = Math.max(maxVowelFreq, frequency[i]);
20            } else {
21                maxConsonantFreq = Math.max(maxConsonantFreq, frequency[i]);
22            }
23        }
24      
25        // Return the sum of the maximum frequency of vowels and consonants
26        return maxVowelFreq + maxConsonantFreq;
27    }
28  
29    // Helper method to determine if a character is a vowel
30    private boolean isVowel(char c) {
31        return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
32    }
33}
34
1#include <string>
2#include <algorithm>
3
4class Solution {
5public:
6    int maxFreqSum(std::string s) {
7        // Frequency array to count occurrences of each character.
8        int frequency[26] = {};
9      
10        // Count frequency of each character in the input string.
11        for (char c : s) {
12            ++frequency[c - 'a'];
13        }
14      
15        // Variables to keep track of the maximum frequency of vowels and consonants.
16        int maxVowelFreq = 0, maxConsonantFreq = 0;
17      
18        // Iterate over each letter in the alphabet to determine max frequencies.
19        for (int i = 0; i < 26; ++i) {
20            char currentChar = 'a' + i;
21            if (currentChar == 'a' || currentChar == 'e' || currentChar == 'i' || currentChar == 'o' || currentChar == 'u') {
22                // Update maximum vowel frequency.
23                maxVowelFreq = std::max(maxVowelFreq, frequency[i]);
24            } else {
25                // Update maximum consonant frequency.
26                maxConsonantFreq = std::max(maxConsonantFreq, frequency[i]);
27            }
28        }
29      
30        // Return the sum of the maximum frequencies of vowels and consonants.
31        return maxVowelFreq + maxConsonantFreq;
32    }
33};
34
1function maxFreqSum(s: string): number {
2    // Create an array to count the frequency of each alphabet character in the string
3    const freqCount: number[] = Array(26).fill(0);
4
5    // Iterate through each character in the string and increase its corresponding count
6    for (const char of s) {
7        // Increment the frequency of the current character
8        ++freqCount[char.charCodeAt(0) - 97];
9    }
10
11    // Initialize variables to store max frequency of vowels and consonants
12    let maxVowelFreq = 0;
13    let maxConsonantFreq = 0;
14
15    // Iterate over each letter in the alphabet
16    for (let i = 0; i < 26; ++i) {
17        // Determine the character corresponding to the current index
18        const char = String.fromCharCode(i + 97);
19
20        // If the character is a vowel, update maxVowelFreq if necessary
21        if ('aeiou'.includes(char)) {
22            maxVowelFreq = Math.max(maxVowelFreq, freqCount[i]);
23        } else { // Otherwise, update maxConsonantFreq if necessary
24            maxConsonantFreq = Math.max(maxConsonantFreq, freqCount[i]);
25        }
26    }
27
28    // Return the sum of the maximum frequencies of vowels and consonants
29    return maxVowelFreq + maxConsonantFreq;
30}
31

Time and Space Complexity

The time complexity of the code is O(n), where n is the length of the string s. This is because the Counter operation iterates over the string once to count the frequency of each character, and the loop iterating over cnt.items() to calculate maximum frequencies is bounded by a constant and thus is effectively O(1) with respect to n.

The space complexity is O(|Σ|), where |Σ| is the size of the alphabet involved. In this case, since the English alphabet is used, |Σ| is 26. The space is used to store the character frequencies in the Counter.


Discover Your Strengths and Weaknesses: Take Our 2-Minute Quiz to Tailor Your Study Plan:

Which of these properties could exist for a graph but not a tree?


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More