Count Vowel Strings in Ranges
Count Vowel Strings in Ranges is a medium arrays & hashing problem solved with the prefix sum strategy pattern.
The best approach, optimal (prefix sums), runs in O(n + q) time and O(n) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from brute force (scan each range) up.
Problem
You are given an array of strings words, indexed from 0, and a 2D integer array queries.
Call a word a vowel string when its first letter and its last letter are both vowels. The vowels are 'a', 'e', 'i', 'o' and 'u'. A word with a single letter is a vowel string exactly when that letter is a vowel.
Each query queries[k] = [l, r] asks how many of the words at indexes l through r, both included, are vowel strings.
Return an integer array ans where ans[k] is the answer to the k-th query.
Examples
Example 1
- Input
words = ["apple","tree","idea","ox","eye","sky"], queries = [[0,2],[1,4],[3,3],[0,5]]- Output
[2,2,0,3]- Why
- The words that start and end with a vowel are "apple" (index 0), "idea" (index 2) and "eye" (index 4). The range 0 to 2 holds two of them, 1 to 4 holds idea and eye, index 3 alone is "ox", which ends in x, and the full range holds all three.
Example 2
- Input
words = ["a","u","bcd","oo"], queries = [[0,3],[2,2],[1,1]]- Output
[3,0,1]- Why
- A one-letter word like "a" starts and ends with the same vowel, so it counts. Only "bcd" fails, so the whole range has 3, index 2 has 0 and index 1 has 1.
Example 3
- Input
words = ["sun","moon"], queries = [[0,1],[1,1]]- Output
[0,0]- Why
- Neither word starts with a vowel, so every answer is 0.
Constraints
1 <= words.length <= 10^51 <= words[i].length <= 40words[i]consists only of lowercase English letters.sum(words[i].length) <= 3 * 10^51 <= queries.length <= 10^50 <= l_i <= r_i < words.length
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 11 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force (scan each range) | O(q · n) | O(1) |
| Optimal (prefix sums) | O(n + q) | O(n) |
1Brute force (scan each range)
O(q · n)Each of the q queries can cover all n words, and each word is checked in constant time.O(1)Only a counter, apart from the answer array that must be returned.For every query, walk from l to r and count the words whose first and last letters are both vowels. Checking one word only looks at two characters, so it costs constant time.
- Write a helper isVowel(c) that is true for a, e, i, o and u.
- For each query [l, r], set count = 0 and, for every i from l to r, add one when words[i] starts and ends with a vowel.
- Store count as the answer to that query.
class Solution {
public int[] vowelStrings(String[] words, int[][] queries) {
int[] ans = new int[queries.length];
for (int k = 0; k < queries.length; k++) {
int count = 0;
for (int i = queries[k][0]; i <= queries[k][1]; i++) {
String w = words[i];
if (isVowel(w.charAt(0)) && isVowel(w.charAt(w.length() - 1))) count++;
}
ans[k] = count;
}
return ans;
}
private boolean isVowel(char c) {
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
}class Solution:
def vowelStrings(self, words: List[str], queries: List[List[int]]) -> List[int]:
ans = []
for l, r in queries:
count = 0
for i in range(l, r + 1):
w = words[i]
if self.isVowel(w[0]) and self.isVowel(w[-1]):
count += 1
ans.append(count)
return ans
def isVowel(self, c: str) -> bool:
return c in "aeiou"class Solution {
public:
vector<int> vowelStrings(vector<string>& words, vector<vector<int>>& queries) {
vector<int> ans(queries.size());
for (int k = 0; k < (int)queries.size(); k++) {
int count = 0;
for (int i = queries[k][0]; i <= queries[k][1]; i++) {
const string& w = words[i];
if (isVowel(w[0]) && isVowel(w.back())) count++;
}
ans[k] = count;
}
return ans;
}
private:
bool isVowel(char c) {
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
};function vowelStrings(words, queries) {
const ans = new Array(queries.length).fill(0);
for (let k = 0; k < queries.length; k++) {
let count = 0;
for (let i = queries[k][0]; i <= queries[k][1]; i++) {
const w = words[i];
if (isVowel(w[0]) && isVowel(w[w.length - 1])) count++;
}
ans[k] = count;
}
return ans;
}
function isVowel(c) {
return c === 'a' || c === 'e' || c === 'i' || c === 'o' || c === 'u';
}2Optimal (prefix sums)
O(n + q)One pass over the words to build the prefix array, then constant work per query.O(n)The prefix array has n + 1 entries (the answer array is required output).Turn every word into a 1 if it starts and ends with a vowel and a 0 otherwise. Then a query just asks for the sum of a range of that 0/1 array, which a prefix sum answers in constant time. Let prefix[i] be how many of the first i words count, with prefix[0] = 0 for the empty prefix. The words in l..r are the first r + 1 words minus the first l words, so the answer is prefix[r + 1] - prefix[l].
- prefix has n + 1 entries and prefix[0] = 0.
- For each i: prefix[i + 1] = prefix[i] + 1 if words[i] starts and ends with a vowel, else prefix[i].
- For each query [l, r]: ans[k] = prefix[r + 1] - prefix[l].
- Return ans.
class Solution {
public int[] vowelStrings(String[] words, int[][] queries) {
int n = words.length;
int[] prefix = new int[n + 1];
for (int i = 0; i < n; i++) {
String w = words[i];
boolean good = isVowel(w.charAt(0)) && isVowel(w.charAt(w.length() - 1));
prefix[i + 1] = prefix[i] + (good ? 1 : 0);
}
int[] ans = new int[queries.length];
for (int k = 0; k < queries.length; k++) {
int l = queries[k][0], r = queries[k][1];
ans[k] = prefix[r + 1] - prefix[l];
}
return ans;
}
private boolean isVowel(char c) {
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
}class Solution:
def vowelStrings(self, words: List[str], queries: List[List[int]]) -> List[int]:
n = len(words)
prefix = [0] * (n + 1)
for i in range(n):
w = words[i]
good = self.isVowel(w[0]) and self.isVowel(w[-1])
prefix[i + 1] = prefix[i] + (1 if good else 0)
ans = []
for l, r in queries:
ans.append(prefix[r + 1] - prefix[l])
return ans
def isVowel(self, c: str) -> bool:
return c in "aeiou"class Solution {
public:
vector<int> vowelStrings(vector<string>& words, vector<vector<int>>& queries) {
int n = words.size();
vector<int> prefix(n + 1, 0);
for (int i = 0; i < n; i++) {
const string& w = words[i];
bool good = isVowel(w[0]) && isVowel(w.back());
prefix[i + 1] = prefix[i] + (good ? 1 : 0);
}
vector<int> ans(queries.size());
for (int k = 0; k < (int)queries.size(); k++) {
int l = queries[k][0], r = queries[k][1];
ans[k] = prefix[r + 1] - prefix[l];
}
return ans;
}
private:
bool isVowel(char c) {
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
};function vowelStrings(words, queries) {
const n = words.length;
const prefix = new Array(n + 1).fill(0);
for (let i = 0; i < n; i++) {
const w = words[i];
const good = isVowel(w[0]) && isVowel(w[w.length - 1]);
prefix[i + 1] = prefix[i] + (good ? 1 : 0);
}
const ans = new Array(queries.length).fill(0);
for (let k = 0; k < queries.length; k++) {
const l = queries[k][0], r = queries[k][1];
ans[k] = prefix[r + 1] - prefix[l];
}
return ans;
}
function isVowel(c) {
return c === 'a' || c === 'e' || c === 'i' || c === 'o' || c === 'u';
}Edge cases to test
- A one-letter vowel word such as "e": its first and last letter are the same vowel, so it counts
- A query with l = r covers a single word
- A query that starts at index 0, which needs the empty prefix (prefix[0] = 0)
- No word qualifies, so every answer is 0
- Every word qualifies, so each answer is r - l + 1
- Many queries over the same long range: re-counting each time is too slow
Hints
Hint 1
First decide, for each word on its own, whether it counts: look only at its first and last letter.
Hint 2
Answering each query by walking its range works, but with 10^5 queries over 10^5 words that is 10^10 steps.
Hint 3
Build prefix[i] = how many of the first i words count. Then the number in l..r is prefix[r + 1] - prefix[l].
FAQ
What is the best time complexity for Count Vowel Strings in Ranges?
Optimal (prefix sums) runs in O(n + q) time and O(n) extra space. One pass over the words to build the prefix array, then constant work per query.
Which pattern does Count Vowel Strings in Ranges use?
It is a arrays & hashing problem that uses the prefix sum strategy pattern. Other problems with the same pattern: Subarray Sum Equals K, Subarray with given XOR, Range Sum Query - Immutable.
Is there a brute force solution for Count Vowel Strings in Ranges?
Yes. Brute force (scan each range) takes O(q · n) time and O(1) space. For every query, walk from l to r and count the words whose first and last letters are both vowels.
Which edge cases should I test for Count Vowel Strings in Ranges?
A one-letter vowel word such as "e": its first and last letter are the same vowel, so it counts; A query with l = r covers a single word; A query that starts at index 0, which needs the empty prefix (prefix[0] = 0); No word qualifies, so every answer is 0; Every word qualifies, so each answer is r - l + 1; Many queries over the same long range: re-counting each time is too slow.