03. Count Vowels in a String

Difficulty:EasyPattern:Set Lookup CountingTime:O(n)Space:O(1)

Count the number of vowels (a, e, i, o, u - case insensitive) in a given string.

How It Works & Algorithmic Design

This applies Set-Based Lookups within a Linear Character Pass:

  1. Vowel Set Lookup: Store target vowels (aeiouAEIOU) in a Hash Set or string lookup table. Checking existence in a Hash Set takes constant time ($O(1)$).
  2. Counting Loop: Iterate over every character ch in the string.
  3. Evaluation: If vowelSet.has(ch), increment count++.
  4. Return: Return the accumulated count.

Why This Approach Works Best

Using a set lookup avoids writing long if-else condition chains. The linear traversal processes the string in $O(n)$ time complexity while requiring only $O(1)$ auxiliary space for the fixed 10-character vowel set.

Example Walkthrough
Input String: "Algorithm"
Mixed case string.
Vowel Checks: 'A' (Yes, count=1) -> 'o' (Yes, count=2) -> 'i' (Yes, count=3)
Matches 'A', 'o', and 'i'.
Output Count: 3
Contains 3 vowels.

Answer: Count vowels using set lookup

function countVowels(s) {
  const vowels = new Set('aeiouAEIOU');
  let count = 0;
  for (const ch of s) {
    if (vowels.has(ch)) count++;
  }
  return count;
}
💡 Inspect characters against a fixed vowel set and accumulate matching counts.
Key Takeaways
  • Hash Set lookups take $O(1)$ constant time.
  • Case sensitivity should be handled by including both uppercase and lowercase vowels in the set.
  • Runs in $O(n)$ linear time relative to string length.