Count Vowels in a String
You are given a string and need to count how many vowel characters it contains.
The vowels for this problem are a, e, i, o, and u. The test data also shows that uppercase vowels should count too, so the check should work for both lowercase and uppercase letters.
For example, if s = "hello", the answer is 2 because the vowels are e and o. If s = "aeiou", the answer is 5 because every character is a vowel. A string like "bcdfg" returns 0 because it contains no vowels at all.
So the task is to scan the string and count exactly the characters that belong to the vowel set.
Example Input & Output
No vowels in the string.
Vowels are 'e' and 'o'.
All characters are vowels.
Algorithm Flow

Solution Approach
The clean Python way to solve this is to loop through the characters and count how many belong to a set of vowels. The main rule is very small, but the implementation should reflect one important detail from the tests: uppercase vowels count too.
One simple approach is to define the vowels as a string or set containing both cases, for example "aeiouAEIOU" or {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}. Then, for each character in the input, check whether it belongs to that collection.
A concise Python version is:
This works by generating a 1 for every character that passes the membership test, then summing those ones together.
You could also normalize the text first with text.lower() and then only compare against lowercase vowels. That is also valid:
Both versions express the same idea. The first keeps the original characters unchanged and includes both cases in the lookup set. The second simplifies the membership set by normalizing case first.
Using a set is a good choice because membership checks like ch in vowels are clear and efficient. You could technically use a string for membership too, but a set makes it obvious that we are checking against a small collection of allowed characters.
This also avoids accidental overthinking. We do not need nested loops, frequency tables, or special handling for consonants. Every character is simply checked once against the vowel collection, and the matches are counted.
The runtime is O(n) because each character is examined once, and the extra space is O(1) because the vowel set has fixed size. This is a straightforward counting problem, and the set membership check makes the intention very clear while still handling uppercase and lowercase input safely.
Best Answers
def count_vowels(text):
# Approach 1: Generator expression
vowels = set('aeiouAEIOU')
return sum(1 for char in text if char in vowels)Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
