Vowel counter
Filed under TCS
Free read 3 of 3Confirm whether spaces and punctuation should be counted as non-vowels or ignored entirely.
The question
Write a function to count the number of vowels and non-vowels (consonants/other characters) in a given string.
Constraints
- The input string can contain uppercase, lowercase, spaces, and special characters.
- Time complexity should be O(n) where n is the length of the string.
Examples
- Input
- s = "Hello World"
- Output
- vowels: 3, non_vowels: 8
- Why
- Vowels are 'e', 'o', 'o'. All other characters including spaces and consonants count as non-vowels.
Approach
Confirm whether spaces and punctuation should be counted as non-vowels or ignored entirely.
Iterate through each character of the string, convert to lowercase, and check if it exists in a predefined vowel set.
Use a single pass with a set lookup for O(1) vowel verification, accumulating counts for vowels and consonants simultaneously.
Handle empty strings, strings with only special characters, and purely uppercase inputs.
Solution
O(n) time, O(1) space
def count_vowels_and_non_vowels(s):
vowels = set("aeiou")
v_count = nv_count = 0
for char in s.lower():
if char.isalpha():
if char in vowels:
v_count += 1
else:
nv_count += 1
else:
nv_count += 1
return v_count, nv_count
Tips
- What they are testing: Tests string traversal, character membership checking, and case-insensitive condition handling.
- Common mistake: Forgetting to account for uppercase vowels or counting spaces/special characters incorrectly.
Related TCS questions
Collected from public candidate posts and coding forums. Updated Nov 2026.