Count the Number of Vowel Strings in Range — Easy Problem & Solution
You are given a 0-indexed array of strings words and two integers left and right.
- Difficulty: Easy
- Topics: Arrays, Strings
- Asked at: TCS, Wipro, Cognizant
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
You are given a 0-indexed array of strings words and two integers left and right.
A string is a vowel string if it both starts and ends with a vowel (a, e, i, o or u). Return how many indices i with left <= i <= right hold a vowel string.
Example 1
Input: words = ["are","amy","u"], left = 0, right = 2
Output: 2
Explanation: "are" starts with a and ends with e; "u" is a single vowel, which counts for both ends; "amy" ends in y.
Example 2
Input: words = ["hey","aeo","mu","ooo","artro"], left = 1, right = 4
Output: 3
Explanation: "aeo", "ooo" and "artro" qualify.
Example 3
Input: words = ["kata","echo"], left = 1, right = 1
Output: 1
Constraints
1 <= words.length <= 10001 <= words[i].length <= 100 <= left <= right < words.lengthwords[i] consists of lowercase English letters.
How to solve Count the Number of Vowel Strings in Range
The predicate touches two characters per word, so the whole problem is a bounded loop with a two-character test.
Approach
- Loop
ifromlefttorightinclusive. - Take
w = words[i]and test whetherw[0]andw[w.length - 1]are both vowels. - Count the words that pass.
Why it works
A word of length 1 has w[0] == w[w.length - 1], so the same test correctly requires that single character to be a vowel — no special case needed.
Complexity
- Time —
O(right - left) - Space —
O(1)
Pitfalls
rightis inclusive;i < rightdrops the last word.- Treating
'y'as a vowel — the statement lists exactly five.
Reference solution
Python
from typing import List
def vowelStrings(words: List[str], left: int, right: int) -> int:
vowels = set("aeiou")
total = 0
for i in range(left, right + 1):
w = words[i]
if w[0] in vowels and w[-1] in vowels:
total += 1
return totalJavaScript
var vowelStrings = function(words, left, right) {
var total = 0;
for (var i = left; i <= right; i++) {
var w = words[i];
if ("aeiou".indexOf(w.charAt(0)) >= 0 && "aeiou".indexOf(w.charAt(w.length - 1)) >= 0) total++;
}
return total;
};Also on the editorial tab: C, C#, C++, Go, Java, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.