Coding problem · Easy · Basics

Count the Vowels

Easy Algorithms & data structures

Return the number of vowels in s. Vowels are a, e, i, o and u, in upper or lower case.

Example 1

Input: s = "Hello World"
Output: 3

Example 2

Input: s = "sky"
Output: 0

Hints

Hint 1

Loop over the characters and check whether each one is in the set of vowels.

Hint 2

Lower-case the character (or the whole string) first so 'A' and 'a' both count.

Write and run your solution

Loading the editor… (JavaScript is required to run code in your browser.)

Solution and explanation

Show the solution

Time O(n) · Space O(1)

Lower-case each character and count it if it's one of the five vowels. A set (or a string of vowels) makes the membership check simple.

Reference solution

function countVowels(s) {
  let count = 0;
  for (const ch of s.toLowerCase()) if ('aeiou'.includes(ch)) count++;
  return count;
}

Was this page helpful?