Count Vowels – Solution & Complexity
Solution Walkthrough
Step 1: Understand What Counts
- Count the vowels
a,e,i,o, andu. - The check is case-insensitive, so uppercase vowels count too.
- Consonants, spaces, digits, and punctuation do not add to the total.
- Count the vowels
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.
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.
Step 4: Handle Edge Cases Naturally
- An empty string returns
0because the loop never increments the count. - Strings with no vowels also return
0. - Uppercase-only inputs work because each character is converted with
lower().
- An empty string returns
Step 5: Final Solution and Complexity
- The solution does one constant-time vowel check per character.
- Time complexity is O(n), where
nis the length of the string. - Space complexity is O(1) because the vowel set has a fixed size.