Count Vowels – Solution & Complexity

Solution Walkthrough

  1. Step 1: Understand What Counts

    • Count the vowels a, e, i, o, and u.
    • The check is case-insensitive, so uppercase vowels count too.
    • Consonants, spaces, digits, and punctuation do not add to the total.
  2. Step 2: Normalize Characters

    • To avoid checking both uppercase and lowercase forms, convert each character to lowercase.
    • Then compare it with a small set of vowel characters.
    • A set gives fast membership checks.
    def count_vowels(s: str) -> int:
        vowels = set('aeiou')
        count = 0
        return count
  3. Step 3: Scan the String Once

    • Iterate through every character in the string.
    • If the lowercase character is in the vowel set, increment the counter.
    • The final counter is the answer.
    def count_vowels(s: str) -> int:
        vowels = set('aeiou')
        count = 0
        for char in s:
            if char.lower() in vowels:
                count += 1
        return count
  4. Step 4: Handle Edge Cases Naturally

    • An empty string returns 0 because the loop never increments the count.
    • Strings with no vowels also return 0.
    • Uppercase-only inputs work because each character is converted with lower().
  5. Step 5: Final Solution and Complexity

    • The solution does one constant-time vowel check per character.
    • Time complexity is O(n), where n is the length of the string.
    • Space complexity is O(1) because the vowel set has a fixed size.
    def count_vowels(s: str) -> int:
        vowels = set('aeiou')
        count = 0
    
        for char in s:
            if char.lower() in vowels:
                count += 1
    
        return count

FAQ