AlgoMaster Logo

Count Vowels and Consonants

Last Updated: June 7, 2026

easy
3 min read

Understanding the Problem

Classify every letter into one of two groups and report how many fall into each. The vowels are a, e, i, o, and u. Every other letter is a consonant.

Two details shape the solution. The comparison is case-insensitive, so both A and a count as the same vowel. Lowercase each character before checking it to fold both cases into one comparison. The string can also hold characters that are neither vowels nor consonants, such as digits, spaces, and punctuation. Those are skipped, so a character only adds to a count when it is a letter.

Take "Programming". Lowercasing it gives "programming". The vowels are o, a, and i, which is 3. The remaining letters p, r, g, r, m, m, n, and g are consonants, which is 8. The answer is [3, 8].

Key Constraints:

  • The check is case-insensitive → A and a are both vowels. Lowercase each character before comparing so you only test against five letters instead of ten.
  • Only letters count → Digits, spaces, and punctuation belong to neither group. In "abc123 xy", the digits and the space are skipped.
  • Return both counts together → The answer is an array of two numbers, with the vowel count first and the consonant count second.

Approach 1: Linear Scan

Intuition

One look at each character decides which group it belongs to. Lowercase it, then ask two questions in order. Is it a letter? If not, skip it. If it is, is it one of the five vowels? If yes, it is a vowel. Otherwise it is a consonant.

Keep two counters and update the right one on each step to build both totals in a single pass.

Algorithm

  1. Initialize vowels to 0 and consonants to 0.
  2. Walk through the string one character at a time.
  3. Convert the current character to lowercase.
  4. If the lowercased character is not between a and z, skip it.
  5. If it is one of a, e, i, o, u, add 1 to vowels. Otherwise add 1 to consonants.
  6. After the scan, return [vowels, consonants].

Example Walkthrough

Input:

0
C
1
o
2
d
3
e
4
1
s

Start with vowels = 0 and consonants = 0. The first character C lowercases to c, a letter that is not a vowel, so consonants becomes 1. The o is a vowel, so vowels becomes 1. The d is a consonant, raising consonants to 2. The e is a vowel, raising vowels to 2. The final character 1 is not a letter, so it is skipped. After the scan, the answer is [2, 2].

0
2
1
2
result

Code