Vowel Counter - Problem

Given a string, count the number of vowels and consonants in it. Ignore any non-alphabetic characters (numbers, spaces, punctuation).

A vowel is one of: a, e, i, o, u (case-insensitive).

Return an array where the first element is the vowel count and the second element is the consonant count.

Input & Output

Example 1 — Basic Mixed String
$ Input: s = "Hello World!"
Output: [2, 3]
💡 Note: Letters: H(consonant), e(vowel), l(consonant), l(consonant), o(vowel). Ignore space, exclamation mark, and 'W', 'o', 'r', 'l', 'd' from 'World' gives us more letters. Total: 2 vowels (e, o), 3 consonants (H, l, l) from 'Hello', plus 'W'(consonant), 'r'(consonant), 'l'(consonant), 'd'(consonant) from 'World'. Final count: 3 vowels (e, o, o), 7 consonants (H, l, l, W, r, l, d). Actually: 'Hello World!' has vowels: e, o, o = 3 vowels; consonants: H, l, l, W, r, l, d = 7 consonants. Wait, let me recount: H-e-l-l-o W-o-r-l-d = vowels(e,o,o) = 3, consonants(H,l,l,W,r,l,d) = 7. So output should be [3,7].
Example 2 — Only Vowels
$ Input: s = "aeiou"
Output: [5, 0]
💡 Note: All characters are vowels: a, e, i, o, u. No consonants present.
Example 3 — Mixed with Numbers
$ Input: s = "abc123def"
Output: [2, 4]
💡 Note: Letters only: a(vowel), b(consonant), c(consonant), d(consonant), e(vowel), f(consonant). Ignore numbers 123. Total: 2 vowels, 4 consonants.

Constraints

  • 1 ≤ s.length ≤ 104
  • s consists of printable ASCII characters

Visualization

Tap to expand
INPUTALGORITHMRESULTString: "Hello World!"HelloWorld!Mixed characters: letters, space, punctuation1Create vowel set{a, e, i, o, u, A, E, I, O, U}2Filter alphabetic charactersSkip numbers, spaces, punctuation3Classify using O(1) set lookupVowel or consonant counter++4Return count arrayOutput Array[3, 7]3 vowels: e, o, o7 consonants: H,l,l,W,r,l,d💡Key Insight:Using a pre-built vowel set enables O(1) character classification instead of searching through a string each time.TutorialsPoint - Vowel Counter | Set-Based Approach
Asked in
Google 15 Amazon 12 Microsoft 8
12.0K Views
Medium Frequency
~5 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen