Problem overview
The function countVowels receives a string s and returns how many vowels it has. The vowels are a, e, i, o and u, in lower or upper case. The letter y does not count. Everything else, such as consonants, spaces, digits and punctuation, is skipped.
In "Hello World" the vowels are e, o and o, so the answer is 3. In "AlgoCademy" they are A, o, a and e, so the answer is 4: the upper-case A counts and the y doesn't. In "Why try?" there are none, so the answer is 0.
Approach
Visit every character once, test whether it is a vowel, and count the ones that are. The test is a lookup in a string that holds all ten vowel characters, upper and lower case. Listing both cases avoids converting each character first.
Going through "Hello World" character by character, only three of the eleven characters pass the test. The counter reaches 1 at the e, 2 at the first o and 3 at the second o. The H, the l characters, the space, the W, the r and the d fail the test and leave the counter alone.
The test is the only place where the exercise's rules live. If the rules changed, for example to count y, you would change the vowels string and nothing else.
Step by step
- Store the vowels in a
valnamedvowels:"aeiouAEIOU". The value never changes, sovalis right. - Create
countwithvar, starting at 0. It changes inside the loop. - Loop over the string with
for (c in s). Each turn gives one character as aChar. - Test the character.
c in vowelsis true whencappears anywhere in the stringvowels. If so, docount++. - Return
countafter the loop, so every character has been checked first.
The solution in Kotlin
class Solution {
fun countVowels(s: String): Int {
val vowels = "aeiouAEIOU"
var count = 0
for (c in s) {
if (c in vowels) {
count++
}
}
return count
}
}
Some details worth knowing:
- A
Stringis a sequence ofChar. Theforloop hands out characters one at a time, in order. ACharis written with single quotes, such as'e', and aStringwith double quotes. inworks on strings.'e' in "aeiou"istrue. The check is case-sensitive:'E' in "aeiou"isfalse, which is why the lesson's string lists both cases.- The loop variable is a
val.cholds a new character on each turn and can't be reassigned inside the loop. - A shorter form exists.
s.count { it in vowels }counts the characters that pass a test and gives 3 on"Hello World". The explicit loop shows what that call does.
Complexity
Time is O(n) for a string of length n, since the lookup in the ten-character vowels string takes a constant number of comparisons. Space is O(1).
Edge cases and common mistakes
- Upper-case vowels. Leaving them out of
vowelsgives 3 instead of 4 for"AlgoCademy". - The letter y. It isn't in the string, so
"Why try?"gives 0. - Returning inside the loop. The function would stop after the first character.
- Counting once per distinct vowel. Every occurrence counts:
"Hello World"has two o's and the answer includes both.
Testing
"Hello World"gives3."AlgoCademy"gives4."Why try?"gives0.
