#332Easy· asked at 1 company
Count Vowels, Consonants, and Spaces in a String
Problem
Given a string s, return three counts: the number of vowels (a e i o u, either case), the number of consonants (all other English letters), and the number of spaces. Digits and punctuation are ignored.
Input / Output
- Input: string
s. - Output:
[vowels, consonants, spaces].
Examples
Example 1
Input: s = "Hello World"
Output: [3, 7, 1]
Example 2
Input: s = "AEIOU xyz"
Output: [5, 3, 1]
Example 3
Input: s = "123 !!"
Output: [0, 0, 1]
Constraints
0 <= s.length <= 10^5
Approach
Single pass; classify each character:
- If it is a space →
spaces++. - Else if it is a letter → lowercase it; if it is in
{a,e,i,o,u}→vowels++, elseconsonants++. - Otherwise ignore.
Use a set for the vowel test (O(1)) rather than a chain of or comparisons. Note that y counts as a consonant here.
Complexity
- Time: O(n)
- Space: O(1)
Reference solution (Python)
def count_vcs(s):
vowels = consonants = spaces = 0
V = set("aeiou")
for c in s:
if c == ' ':
spaces += 1
elif c.isalpha():
if c.lower() in V:
vowels += 1
else:
consonants += 1
return [vowels, consonants, spaces]
Test cases
| Input | Expected |
|---|---|
"Hello World" | [3,7,1] |
"AEIOU xyz" | [5,3,1] |
"123 !!" | [0,0,1] |
"" | [0,0,0] |