Problem 8: Count Vowels

Published: (January 6, 2026 at 01:05 AM EST)
1 min read
Source: Dev.to

Source: Dev.to

Examples

count_vowels("hello world")  # โ†’ 3
count_vowels("AEIOU")        # โ†’ 5

Solution

def count_vowels(s):
    """
    Counts the number of vowels in a string.
    """
    vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}
    count = 0
    for char in s:
        if char in vowels:
            count += 1
    return count

# Test case
print(count_vowels("pooopcycle"))  # Output: 4

Walkthrough

  • Function definition: def count_vowels(s): creates a function that accepts a string s.

  • Vowel set: vowels = {...} stores all lowercase and uppercase vowels in a set for O(1) lookups.

  • Counter initialization: count = 0 starts the vowel counter.

  • Iteration: for char in s: loops through each character in the input string.

  • Check & increment:

    if char in vowels:
        count += 1

    Increments count when the current character is a vowel.

  • Return: return count provides the total number of vowels found.

Example trace for "pooopcycle"

CharacterIn vowels?Count
pNo0
oYes1
oYes2
oYes3
pNo3
cNo3
yNo3
cNo3
lNo3
eYes4

The function correctly returns 4 for this input.

Happy coding! ๐Ÿ’ป

Back to Blog

Related posts

Read more ยป

Day 85 of 100 days dsa coding challenge

Challenge Overview Taking on a new challenge: solving GeeksforGeeks POTD daily and sharing my solutions! ๐Ÿ’ป๐Ÿ”ฅ Problem Minimum time to fulfil all orders Geeksfo...

Coding Challenge Practice - Question 97

Problem Description The task is to find the kโ€‘th largest element in an unsorted array that may contain duplicates. The kโ€‘th largest element is the element that...