Count Vowel Strings in Ranges (LeetCode 2559): Solution and Explanation

Medium
Array
String
Prefix Sum

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

  1. Create prefix of length n + 1 with prefix[0] = 0.
  2. For each word i, set prefix[i + 1] = prefix[i] + 1 if its first and last letters are both vowels, otherwise prefix[i + 1] = prefix[i].
  3. For each query [l, r], append prefix[r + 1] - prefix[l] to the answer.
  4. Return the answer array.

Step-by-step example

words = ["aba","bcb","ece","aa","e"], queries = [[0,2],[1,4],[1,1]]
  1. Marks are [1,0,1,1,1], since only "bcb" starts and ends with consonants.
  2. Prefix counts are [0,1,1,2,3,4].
  3. [0,2]: prefix[3] - prefix[0] = 2 - 0 = 2. [1,4]: prefix[5] - prefix[1] = 4 - 1 = 3.
  4. [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 ans
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n + q)

One pass over the n words builds the prefix array, and each of the q queries takes O(1).

Space

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).