Write a function `countVowels(str)` that returns the number of vowels (a, e, i, o, u) in the string (case-insensitive).
Problem Statement
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
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
- Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
- Choose Core Mechanism: Use modern JavaScript patterns (convert the string to lowercase first).
- Implement Logic: Handle state and transformations efficiently (you can use a regex match or iterate through each character).
- 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
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.