Skip to main content

Count Vowels and Consonants

EasyProblem

Description

Given a string s, return [vowels, consonants]: how many of its characters are vowels and how many are consonants.

The vowels are a, e, i, o and u, in either case; the consonants are the other 21 letters, y included. Characters that aren't letters, like spaces, digits and punctuation, count as neither.

Examples

Example 1

Input: s = "Hi, Bob"

Output: [2, 3]

Explanation: The vowels are i and o; the consonants H, B and b. The comma and the space count as neither.

Example 2

Input: s = "AEIOU aeiou"

Output: [10, 0]

Explanation: Ten vowels, capital or not, and no consonants.

Example 3

Input: s = "123 !?"

Output: [0, 0]

Explanation: No letters at all.

Example 4

Input: s = "Rhythm"

Output: [0, 6]

Explanation: y counts as a consonant here, so all 6 letters are consonants.

Constraints

  • 1 ≤ s.length ≤ 10^5
  • s consists of printable ASCII characters

Editorial

Approach - Sort Each Character

Intuition

Every character falls into one of three groups: a vowel (a, e, i, o or u, in either case), any other letter, which is a consonant, or something that isn't a letter at all, like a space, a digit or a comma. One pass that asks the two questions in that order counts both.

Ask "is it a vowel?" first, then "is it a letter?": a character that fails the first but passes the second is a consonant, and one that fails both is neither.

Step-by-Step Explanation

Let's trace Example 1, s = "Hi, Bob":

  1. Vowels, in either case: i, o, so 2.
  2. Other letters: H, B, b, so 3 consonants.
  3. The comma and the space are neither.
  4. Return [2, 3].

Vowel, Consonant or Neither — Green for a vowel, teal for a consonant; the comma and the space stay plain.

Algorithm

  1. Start both counts at 0.
  2. For each character: if it's one of aeiouAEIOU, add 1 to the vowels; otherwise, if it's a letter, add 1 to the consonants.
  3. Return [vowels, consonants].

Code

class Solution {
public:
    vector<int> countVowelsAndConsonants(string& s) {
        int vowels = 0, consonants = 0;
        for (char c : s) {
            if (string("aeiouAEIOU").find(c) != string::npos) vowels++;
            else if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) consonants++;  // any other letter
        }
        return {vowels, consonants};
    }
};
from typing import List

class Solution:
    def countVowelsAndConsonants(self, s: str) -> List[int]:
        vowels = consonants = 0
        for c in s:
            if c in "aeiouAEIOU":
                vowels += 1
            elif ("a" <= c <= "z") or ("A" <= c <= "Z"):    # any other letter
                consonants += 1
        return [vowels, consonants]
class Solution {
    public int[] countVowelsAndConsonants(String s) {
        int vowels = 0, consonants = 0;
        for (char c : s.toCharArray()) {
            if ("aeiouAEIOU".indexOf(c) >= 0) vowels++;
            else if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) consonants++;  // any other letter
        }
        return new int[] {vowels, consonants};
    }
}
var countVowelsAndConsonants = function(s) {
    let vowels = 0, consonants = 0;
    for (const c of s) {
        if ("aeiouAEIOU".includes(c)) vowels++;
        else if ((c >= "a" && c <= "z") || (c >= "A" && c <= "Z")) consonants++;  // any other letter
    }
    return [vowels, consonants];
};

Complexity Analysis

Time Complexity: O(n)

Each character is looked at once.

Space Complexity: O(1)

Two counts.

Common Mistakes

Each of these looks right on a quick read, and the tests still reject it. The outputs below come from running the code.

Checking lowercase vowels only. if c in "aeiou":

On s = "AEIOU aeiou" it returns [5, 5]; the answer is [10, 0]. c in "aeiou" misses the capitals, so A, E, I, O and U are counted as consonants. Check both cases, or lowercase each character first.

Counting everything else as a consonant. len(s) - vowels

On s = "Hi, Bob" it returns [2, 5]; the answer is [2, 3]. A consonant is a letter that isn't a vowel. Spaces, digits and punctuation aren't letters, so they count as neither.

Counting y as a vowel. "aeiouyAEIOUY"

On s = "Rhythm" it returns [1, 5]; the answer is [0, 6]. The problem names its vowels: a, e, i, o and u. y is one of the 21 consonants, even in words like "rhythm" where it sounds like a vowel.

Where This Pattern Is Taught

This problem practises one pass over a string, testing each character. It's taught in Introduction to Strings.