Count Vowel Strings in Ranges (LeetCode 2559): Solution and Explanation
Count how many words in each query range start and end with a vowel. A prefix-sum array built in one pass answers every query in constant time.
Intuition
Whether a word counts depends only on its first and last letters, so each word can be marked 1 or 0 once, before any query is read.
Each query then asks for the sum of the marks between l and r. Summing the range directly costs up to n steps per query, and with 10^5 queries that is far too slow.
A prefix-sum array fixes this: prefix[k] is the number of good words among the first k words. The count inside [l, r] is everything up to r minus everything before l, which is prefix[r + 1] - prefix[l].
Building the prefix array takes one pass over the words, and after that every query is a single subtraction.
Approach: Prefix sums
- Create
prefixof length n + 1 withprefix[0] = 0. - For each word i, set
prefix[i + 1] = prefix[i] + 1if its first and last letters are both vowels, otherwiseprefix[i + 1] = prefix[i]. - For each query
[l, r], appendprefix[r + 1] - prefix[l]to the answer. - Return the answer array.
Step-by-step example
words = ["aba","bcb","ece","aa","e"], queries = [[0,2],[1,4],[1,1]]
- Marks are [1,0,1,1,1], since only "bcb" starts and ends with consonants.
- Prefix counts are [0,1,1,2,3,4].
- [0,2]: prefix[3] - prefix[0] = 2 - 0 = 2. [1,4]: prefix[5] - prefix[1] = 4 - 1 = 3.
- [1,1]: prefix[2] - prefix[1] = 1 - 1 = 0. The answer is [2,3,0].
Code: Python, Java, C++
1class Solution:
2 def vowelStrings(self, words: List[str], queries: List[List[int]]) -> List[int]:
3 vowels = set("aeiou")
4 prefix = [0]
5 for w in words:
6 prefix.append(prefix[-1] + (w[0] in vowels and w[-1] in vowels))
7 ans = []
8 for l, r in queries:
9 ans.append(prefix[r + 1] - prefix[l])
10 return ans1class Solution {
2 public int[] vowelStrings(String[] words, int[][] queries) {
3 String vowels = "aeiou";
4 int[] prefix = new int[words.length + 1];
5 for (int i = 0; i < words.length; i++) {
6 String w = words[i];
7 boolean good = vowels.indexOf(w.charAt(0)) >= 0 && vowels.indexOf(w.charAt(w.length() - 1)) >= 0;
8 prefix[i + 1] = prefix[i] + (good ? 1 : 0);
9 }
10 int[] ans = new int[queries.length];
11 for (int q = 0; q < queries.length; q++) {
12 ans[q] = prefix[queries[q][1] + 1] - prefix[queries[q][0]];
13 }
14 return ans;
15 }
16}1class Solution {
2public:
3 vector<int> vowelStrings(vector<string>& words, vector<vector<int>>& queries) {
4 auto isVowel = [](char c) { return string("aeiou").find(c) != string::npos; };
5 vector<int> prefix(words.size() + 1, 0);
6 for (int i = 0; i < (int)words.size(); i++) {
7 bool good = isVowel(words[i].front()) && isVowel(words[i].back());
8 prefix[i + 1] = prefix[i] + (good ? 1 : 0);
9 }
10 vector<int> ans;
11 for (auto& q : queries) {
12 ans.push_back(prefix[q[1] + 1] - prefix[q[0]]);
13 }
14 return ans;
15 }
16};Time and space complexity
O(n + q)
One pass over the n words builds the prefix array, and each of the q queries takes O(1).
O(n)
The prefix array has n + 1 entries, not counting the output.
Other approaches
Scan each range (time O(n * q), space O(1))
For every query, loop from l to r and count good words. Simple, but O(n) per query, which times out when both n and q reach 10^5.
Fenwick tree (time O((n + q) log n), space O(n))
A binary indexed tree also answers range counts in O(log n) and would support updates to words, but the words never change here, so plain prefix sums are simpler and faster.
Common mistakes
- Using prefix[r] - prefix[l] instead of prefix[r + 1] - prefix[l]. The range is inclusive on both ends, so the right edge needs the + 1.
- Checking only the first letter, or only whether the word contains a vowel. Both the first and the last letter must be vowels.
- Forgetting one-letter words. For "e" the first and last letter are the same character, and it counts.
- Recomputing the vowel check inside each query instead of once per word.
Frequently asked questions
Why is the prefix array one longer than words?
prefix[0] = 0 stands for the empty prefix, so a range starting at l = 0 subtracts 0 without a special case.
Does the order of queries matter?
No. Each query is answered independently from the same prefix array.
Would this work if words could change between queries?
Not efficiently, since one change shifts every later prefix value. A Fenwick tree or segment tree handles updates in O(log n).