DDSA Solutions

3541. Find Most Frequent Vowel and Consonant

Time: O(n)
Space: O(26)
Advertisement

Approach

Count vowel and consonant frequencies; return max-freq vowel + max-freq consonant.

Key Techniques

Hash Table

Hash tables provide O(1) average-case lookup, insert, and delete. They are the go-to tool for counting frequencies, detecting complements (Two Sum pattern), and caching seen values. In C#, use Dictionary<K,V> for maps and HashSet<T> for membership checks.

String

String problems range from simple character counting to complex pattern matching. Common approaches include two pointers, sliding window, prefix hashing, and the KMP algorithm. In C#, strings are immutable — use StringBuilder for efficient concatenation inside loops.

Counting

Counting problems enumerate valid configurations without explicitly generating them. Techniques: combinatorics (nCr), inclusion-exclusion, digit DP, and contribution of each element. In C#, use long to avoid overflow when multiplying counts.

3541.cs
C#
// Approach: Count vowel and consonant frequencies; return max-freq vowel + max-freq consonant.
// Time: O(n) Space: O(26)

public class Solution
{
    public int MaxFreqSum(string s)
    {
        // Array to store frequency count of each letter (a-z)
        int[] frequencyCount = new int[26];

        // Count the frequency of each character in the string
        foreach (char character in s)
            frequencyCount[character - 'a']++;

        // Variables to track maximum frequency among vowels and consonants
        int maxVowelFrequency = 0;
        int maxConsonantFrequency = 0;

        // Iterate through the frequency array to find max frequencies
        for (int i = 0; i < frequencyCount.Length; i++)
        {
            char currentChar = (char)(i + 'a');

            // Check if current character is a vowel
            if (currentChar == 'a' || currentChar == 'e' || currentChar == 'i' ||
                currentChar == 'o' || currentChar == 'u')
                // Update maximum vowel frequency if current is greater
                maxVowelFrequency = Math.Max(maxVowelFrequency, frequencyCount[i]);
            else
                // Update maximum consonant frequency if current is greater
                maxConsonantFrequency = Math.Max(maxConsonantFrequency, frequencyCount[i]);
        }

        // Return the sum of maximum vowel frequency and maximum consonant frequency
        return maxVowelFrequency + maxConsonantFrequency;
    }
}
Advertisement
Was this solution helpful?