← TCS questions

Vowel counter

Filed under TCS

Free read 3 of 3

Confirm 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

  1. Confirm whether spaces and punctuation should be counted as non-vowels or ignored entirely.

Solution

O(n) time, O(1) space

Python
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.