Skip to content

3541. Find Most Frequent Vowel and Consonant 👍

  • Time: $O(n)$
  • Space: $O(26) = O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
 public:
  int maxFreqSum(string s) {
    vector<int> count(26);
    int maxVowel = 0;
    int maxConsonant = 0;

    for (const char c : s)
      ++count[c - 'a'];

    for (const char c : s)
      if (isVowel(c))
        maxVowel = max(maxVowel, count[c - 'a']);
      else
        maxConsonant = max(maxConsonant, count[c - 'a']);

    return maxVowel + maxConsonant;
  }

 private:
  bool isVowel(char c) {
    static constexpr string_view kVowels = "aeiou";
    return kVowels.find(c) != string_view::npos;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
  public int maxFreqSum(String s) {
    int[] count = new int[26];
    int maxVowel = 0;
    int maxConsonant = 0;

    for (final char c : s.toCharArray())
      ++count[c - 'a'];

    for (final char c : s.toCharArray())
      if (isVowel(c))
        maxVowel = Math.max(maxVowel, count[c - 'a']);
      else
        maxConsonant = Math.max(maxConsonant, count[c - 'a']);

    return maxVowel + maxConsonant;
  }

  private boolean isVowel(char c) {
    return "aeiou".indexOf(c) != -1;
  }
}
1
2
3
4
5
6
7
class Solution:
  def maxFreqSum(self, s: str) -> int:
    VOWELS = 'aeiou'
    count = collections.Counter(s)
    maxVowel = max((count[c] for c in VOWELS if c in count), default=0)
    maxConsonant = max((count[c] for c in count if c not in VOWELS), default=0)
    return maxVowel + maxConsonant