Photo belongs to Joshua Hoehne in Unsplash
Welcome! Today I'll show you a commonly asked algorithm in tech interviews: the vowel counter.
As you can see if you’ve been following my series, the most frequently asked algorithms are related with Arrays, that’s why we started with that data structrue in the first post. Well, this problem will be solved using it too.
So, let’s start!
Problem Statement
Given a string, count the number of vowels it contains. Vowels are the characters 'a', 'e', 'i', 'o', and 'u'.
Easy, right? While straightforward, this problem is excellent for learning fundamental concepts like loops and string manipulation.
The problem statement clearly defines both the input (a string) and the output (a number). It also hints at the solution by listing the specific characters we need to count. Let me demonstrate this better with code.
Algorithm to solve it
- Declare a
count
variable to register each appearance of a vowels in the input.
let count = 0;
- Next, create an array with the expected chars to be found, do you remember that I mentioned in the problem statement? Well, this is why. We need an array with each vowel to check if the input string contains any fo this characters.
const checker = ['a', 'e', 'i', 'o', 'u'];
- Next, we need to loop each character in the input string using a for…of.
// convert to lowerCase to prevent mismatch
for(let char of str.toLowerCase()) {}
- We need to check if the
char
is part of our checker. The vowels, and for this we are going to use the includes method.
if(checker.includes(char))
- If
checker
includeschar
: if the character is a vowel in simple words, increment thecount
variable. Otherwise, continue with the next iteration.
if(checker.includes(char)){
// the char is a vowel
count++;
}
- Return the count of vowels in the input string.
return count;
As you can see this is an easy one, but a helpful to master the basics, since we covered strings manipulation, array methods and loops. So, if you are starting in CS, it is a good starting point.
Typescript Implementation
export function vowels(str: string): number{
let count = 0;
const checker = ['a', 'e', 'i', 'o', 'u'];
for(let char of str.toLowerCase()) {
if(checker.includes(char)) {
count++;
}
}
return count;
}
Conclusion
Voila! Now you know how to count vowels in a string. For an extra challenge, consider: how would you modify this code to count each vowel separately? That is, counting how many a
's, e
's, and so on.
As you can see, learning algorithms isn't rocket science, but it requires patience and, most importantly, a clear path. You need to master the basics and build from there—otherwise, you'll just memorize solutions without understanding the logic behind them.
And remember, you can check this and other algorithms in my repo. I'm planning to include them in other languages.
In our next post, we'll explore the word count algorithm. Stay tuned!
Top comments (0)