Explorer
JavaScript

Write a function `countVowels(str)` that returns the number of vowels (a, e, i, o, u) in the string (case-insensitive).

Problem Statement

<p>Write a function <code>countVowels(str)</code> that returns the number of vowels (a, e, i, o, u) in the string (case-insensitive).</p>

Examples

Input: str = "hello"

Output: 2

Explanation: Vowels are "e" and "o".

Input: str = "JavaScript"

Output: 3

Explanation: Vowels are "a", "a", and "i".

Complexity

Time Complexity: O(N)

Space Complexity: O(1)

Hints

šŸ’” Hint 1: Convert the string to lowercase first. šŸ’” Hint 2: You can use a regex match or iterate through each character. šŸ’” Hint 3: Use match with regex: (str.match(/[aeiou]/gi) || []).length

Editorial & Approach

Problem Overview & Intuition

To solve Count Vowels, we consider the execution characteristics of JavaScript engines. Write a function `countVowels(str)` that returns the number of vowels (a, e, i, o, u) in the string (case-insensitive). By utilizing idiomatic language constructs and clean algorithmic principles, we can accomplish this with optimal time and memory usage.

Step-by-Step Approach

  1. Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
  2. Choose Core Mechanism: Use modern JavaScript patterns (convert the string to lowercase first).
  3. Implement Logic: Handle state and transformations efficiently (you can use a regex match or iterate through each character).
  4. Return Result: Ensure proper return format and preserve caller context if applicable.

Optimal Implementation (JavaScript)

function countVowels(str) {
  return (str.match(/[aeiou]/gi) || []).length;
}

Complexity Analysis

Time Complexity O(N) linear scan over input
Space Complexity O(1) constant auxiliary space (or O(N) output)

Edge Cases & Corner Traps Handled

  • Empty or boundary inputs (empty arrays, strings, zero length).
  • Type checks and unexpected values (e.g. null, undefined, negative numbers).
  • Closure preservation and memory isolation between separate invocations.

Count Vowels

Easy

Write a function countVowels(str) that returns the number of vowels (a, e, i, o, u) in the string (case-insensitive).

Example Scenarios
1Example 1
Input: str = "hello"
Output: 2
Explanation:

Vowels are "e" and "o".

2Example 2
Input: str = "JavaScript"
Output: 3
Explanation:

Vowels are "a", "a", and "i".

Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
[2,3,0]