Problem Statement
Count the number of vowels (a, e, i, o, u) in a given string.
Example Inputs
- Input:
"hello"
- Input:
"JavaScript"
- Input:
"java"
- Input:
"Education"
JavaScript Method - Using Only String Methods
Approach
To count the vowels in a string, we can convert the string to lowercase to handle case insensitivity, then use the .split()
and .filter()
methods to isolate vowels and count them.
Steps
- Convert the string to lowercase using
.toLowerCase()
.
- Split the string into an array of characters with
.split('')
.
- Use
.filter()
to create a new array containing only vowels (a, e, i, o, u).
- Return the length of the array to get the count of vowels.
Time & Space Complexity
- Time Complexity: O(n), where n is the length of the string, as we iterate over each character once.
- Space Complexity: O(n), due to the creation of a new array for filtered vowels.
Code Snippet
Dry Run
Example input: "hello"
- Step 1:
str.toLowerCase()
→ "hello"
- Step 2:
"hello".split('')
→ ['h', 'e', 'l', 'l', 'o']
- Step 3:
filter(['h', 'e', 'l', 'l', 'o'])
→ ['e', 'o']
- Step 4: Return
['e', 'o'].length
→ 2
Alternative Approach - Without Using JavaScript String Methods
Approach
In this approach, we loop through the string and manually count vowels by checking each character. This avoids using JavaScript string methods directly.
Steps
- Initialize a variable
count
to zero.
- Loop through each character of the string.
- Convert the character to lowercase (using conditional checks instead of methods).
- Check if the character is a vowel (a, e, i, o, u).
- If it is, increment the
count
variable by one.
- Return the
count
after the loop ends.
Time & Space Complexity
- Time Complexity: O(n), as we traverse each character once.
- Space Complexity: O(1), as we only use a counter variable.
Code Snippet
Dry Run
Example input: "hello"
- Initialize:
count = 0
- Loop through
"hello"
:
h
→ Not a vowel, count = 0
e
→ Vowel, count = 1
l
→ Not a vowel, count = 1
l
→ Not a vowel, count = 1
o
→ Vowel, count = 2
- Final output:
2
Complexity Analysis
JavaScript Method (Using String Methods)
- Time Complexity: O(n)
- Space Complexity: O(n)
Alternative Approach (Without String Methods)
- Time Complexity: O(n)
- Space Complexity: O(1)
Conclusion
Counting vowels in a string can be done using string methods like split
and filter
for simplicity or with a loop for efficiency. Both methods have similar time complexities, but the manual loop approach saves space by avoiding additional arrays.