This problem requires finding the most frequently occurring vowel and consonant characters in a string, and returning the sum of their frequencies.
Steps
- Initialize a character frequency map using a loop.
- Define a list of vowels:
['a', 'e', 'i', 'o', 'u']. - Traverse the string and count how often each character appears.
- Track the highest frequency vowel and the highest frequency consonant.
- Return the sum of those two highest values.
Dry Run
Input: s = "successes"
- Frequency map: { s: 4, u: 1, c: 2, e: 2 }
- Vowels: u(1), e(2) →
maxVowels = 2 - Consonants: s(4), c(2) →
maxConsonant = 4 - Output:
2 + 4 = 6
Time & Space Complexity
- Time Complexity: O(n), where n = length of the string
- Space Complexity: O(k), where k = number of unique characters (at most 26 lowercase letters)
var maxFreqSum = function (s) {
let map = {}
for (i = 0; i < s.length; i++) {
if (!map[s[i]]) {
map[s[i]] = 1
} else {
++map[s[i]]
}
}
let vowels = ['a', 'e', 'i', 'o', 'u']
let maxVowels = 0
let maxConsonant = 0
for (let i = 0; i < s.length; i++) {
if (vowels.includes(s[i])) {
if (map[s[i]] > maxVowels) {
maxVowels = map[s[i]]
}
}
else {
if (map[s[i]] > maxConsonant) {
maxConsonant = map[s[i]]
}
}
}
return maxConsonant + maxVowels
};
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
int maxFreqSum(string s) {
unordered_map <char,int> freq;
for (char c : s) freq[c]++;
string vowels = "aeiou";
int maxV = 0, maxC = 0;
for (auto &p : freq) {
char ch = p.first;
int cnt = p.second;
if (vowels.find(ch) != string::npos) {
maxV = max(maxV, cnt);
} else {
maxC = max(maxC, cnt);
}
}
return maxV + maxC;
}
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int maxFreqSum(char* s) {
int freq[256] = {0};
for (int i = 0; s[i]; i++) freq[(unsigned char)s[i]]++;
char* vowels = "aeiou";
int maxV = 0, maxC = 0;
for (int i = 0; s[i]; i++) {
unsigned char ch = s[i];
if (strchr(vowels, ch)) {
if (freq[ch] > maxV) maxV = freq[ch];
} else if (isalpha(ch)) {
if (freq[ch] > maxC) maxC = freq[ch];
}
}
return maxV + maxC;
}
import java.util.*;
public class Solution {
public int maxFreqSum(String s) {
Map<Character,Integer> freq = new HashMap<>();
for (char c : s.toCharArray())
freq.put(c, freq.getOrDefault(c,0) + 1);
Set<Character> vowels = Set.of('a','e','i','o','u');
int maxV = 0, maxC = 0;
for (var entry : freq.entrySet()) {
char ch = entry.getKey();
int cnt = entry.getValue();
if (vowels.contains(ch)) {
maxV = Math.max(maxV, cnt);
} else {
maxC = Math.max(maxC, cnt);
}
}
return maxV + maxC;
}
}
def maxFreqSum(s):
from collections import Counter
freq = Counter(s)
vowels = set('aeiou')
maxV = max((freq[ch] for ch in freq if ch in vowels), default=0)
maxC = max((freq[ch] for ch in freq if ch not in vowels), default=0)
return maxV + maxC
