Home
DSA Patterns
Prefix Sum
Count Vowels in Ranges
Count Vowels in Ranges
Count Vowels in Ranges: answer range queries counting the words that start and end with a vowel: one pass to build a prefix count, then one subtraction per query.
Problem Understanding
You are given a string array words and a 2D array queries. Each query [l, r] asks for the number of strings in words[l...r] that start and end with a vowel.
We need to answer many queries efficiently.
Strategy
- Preprocessing: Create a boolean/integer array
is_validwhereis_valid[i] = 1ifwords[i]starts and ends with a vowel, else 0. - Prefix Sum: Compute prefix sum
Pofis_valid.P[i]= count of valid words inwords[0...i-1]. - Query: Answer for
[l, r]isP[r+1] - P[l].
Vowels: a, e, i, o, u
Interactive Visualization
5 WORDS · 3 QUERIES
ALLOCATE PREFIX
words
0
1
2
3
4
valid (0/1)
0
1
2
3
4
prefix
0
1
2
3
4
5
Query
:
Answer
:
ans
No query answered yet
Allocate prefix with 6 zeros: prefix[i] will count the vowel strings among the first i words
Next
"aba" starts with 'a' and ends with 'a': both vowels, so it counts
Words
Queries
See how we can answer multiple range queries in O(1) time after O(N) preprocessing.
Edge Cases
Consider:
Empty Queries: Return empty array.
Single Word: Range [0, 0].
No Vowels: Prefix sum remains 0.
Dry Run
Words: ['aba', 'bcb', 'ece', 'aa', 'e']. Valid: [1, 0, 1, 1, 1].
Prefix P: [0, 1, 1, 2, 3, 4] (size N+1)
| Query | Formula P[R+1] - P[L] |
Values | Result |
|---|---|---|---|
[0, 2] |
P[3] - P[0] |
2 - 0 | 2 (aba, ece) |
[1, 4] |
P[5] - P[1] |
4 - 1 | 3 (ece, aa, e) |
Solution
O(N + Q) Time.
Count Vowels in Ranges Code
1var vowelStrings = function(words, queries) {2 const vowels = new Set(['a', 'e', 'i', 'o', 'u']);3 const n = words.length;4 const prefix = new Array(n + 1).fill(0);56 for (let i = 0; i < n; i++) {7 const w = words[i];8 const valid = vowels.has(w[0]) && vowels.has(w[w.length - 1]);9 prefix[i+1] = prefix[i] + (valid ? 1 : 0);10 }1112 const ans = [];13 for (const [l, r] of queries) {14 ans.push(prefix[r+1] - prefix[l]);15 }16 return ans;17};
Count Vowels in Ranges in Python, Java, C++, TypeScript and C
Count Vowels in Ranges in Python
class Solution:
def vowelStrings(self, words: List[str], queries: List[List[int]]) -> List[int]:
vowels = {'a', 'e', 'i', 'o', 'u'}
n = len(words)
prefix = [0] * (n + 1)
for i in range(n):
w = words[i]
is_valid = 1 if w[0] in vowels and w[-1] in vowels else 0
prefix[i+1] = prefix[i] + is_valid
ans = []
for l, r in queries:
ans.append(prefix[r+1] - prefix[l])
return ansCount Vowels in Ranges in Java
class Solution {
public int[] vowelStrings(String[] words, int[][] queries) {
int n = words.length;
int[] prefix = new int[n + 1];
Set<Character> vowels = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u'));
for (int i = 0; i < n; i++) {
String w = words[i];
boolean isValid = vowels.contains(w.charAt(0)) && vowels.contains(w.charAt(w.length() - 1));
prefix[i+1] = prefix[i] + (isValid ? 1 : 0);
}
int[] ans = new int[queries.length];
for (int i = 0; i < queries.length; i++) {
ans[i] = prefix[queries[i][1] + 1] - prefix[queries[i][0]];
}
return ans;
}
}Count Vowels in Ranges in C++
class Solution {
bool isVowel(char c) {
return c=='a' || c=='e' || c=='i' || c=='o' || c=='u';
}
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++) {
bool valid = isVowel(words[i][0]) && isVowel(words[i].back());
prefix[i+1] = prefix[i] + (valid ? 1 : 0);
}
vector<int> ans;
for(auto& q : queries) {
ans.push_back(prefix[q[1] + 1] - prefix[q[0]]);
}
return ans;
}
};Count Vowels in Ranges in TypeScript
function vowelStrings(words: string[], queries: number[][]): number[] {
const vowels = new Set(['a', 'e', 'i', 'o', 'u']);
const n = words.length;
const prefix: number[] = new Array(n + 1).fill(0);
for (let i = 0; i < n; i++) {
const w = words[i];
const valid = vowels.has(w[0]) && vowels.has(w[w.length - 1]);
prefix[i+1] = prefix[i] + (valid ? 1 : 0);
}
const ans: number[] = [];
for (const [l, r] of queries) {
ans.push(prefix[r+1] - prefix[l]);
}
return ans;
};Count Vowels in Ranges in C
bool isVowel(char c) {
return c=='a' || c=='e' || c=='i' || c=='o' || c=='u';
}
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* vowelStrings(char** words, int wordsSize, int** queries, int queriesSize, int* queriesColSize, int* returnSize) {
int* prefix = (int*)calloc(wordsSize + 1, sizeof(int));
for(int i=0; i<wordsSize; i++) {
int len = strlen(words[i]);
bool valid = isVowel(words[i][0]) && isVowel(words[i][len-1]);
prefix[i+1] = prefix[i] + (valid ? 1 : 0);
}
int* ans = (int*)malloc(queriesSize * sizeof(int));
for(int i=0; i<queriesSize; i++) {
int l = queries[i][0];
int r = queries[i][1];
ans[i] = prefix[r+1] - prefix[l];
}
free(prefix);
*returnSize = queriesSize;
return ans;
}More practice: DSA interview questions with answers · patterns cheat sheet
