Count Vowel Strings in Ranges - Problem

You are given a 0-indexed array of strings words and a 2D array of integers queries.

Each query queries[i] = [li, ri] asks us to find the number of strings present at the indices ranging from li to ri (both inclusive) of words that start and end with a vowel.

Return an array ans of size queries.length, where ans[i] is the answer to the ith query.

Note: The vowel letters are 'a', 'e', 'i', 'o', and 'u'.

Input & Output

Example 1 — Basic Case
$ Input: words = ["aba","bcb","ece","aa","e"], queries = [[0,2],[1,4]]
Output: [2,3]
💡 Note: Query [0,2]: "aba"✗, "bcb"✓, "ece"✓ → count = 2. Query [1,4]: "bcb"✓, "ece"✓, "aa"✗, "e"✓ → count = 3.
Example 2 — Single Elements
$ Input: words = ["a","e","i"], queries = [[0,2],[0,1]]
Output: [3,2]
💡 Note: All single vowel strings qualify. Query [0,2]: all 3 strings qualify. Query [0,1]: first 2 strings qualify.
Example 3 — No Valid Strings
$ Input: words = ["hello","world","code"], queries = [[0,2]]
Output: [0]
💡 Note: "hello" starts with 'h', "world" starts with 'w', "code" ends with 'e' but starts with 'c'. None qualify.

Constraints

  • 1 ≤ words.length ≤ 105
  • 1 ≤ words[i].length ≤ 40
  • words[i] consists only of lowercase English letters
  • sum(queries.length) ≤ 3 × 105
  • 0 ≤ queries[i][0] ≤ queries[i][1] < words.length

Visualization

Tap to expand
Count Vowel Strings in Rangeswords = ["aba", "bcb", "ece", "aa", "e"], queries = [[0,2], [1,4]]ababcbeceaae01234Check: starts AND ends with vowel (a,e,i,o,u)?a→a ✗b→b ✓e→e ✓a→a ✗e→e ✓Query [0,2]Count: 0 + 1 + 1 = 2Query [1,4]Count: 1 + 1 + 0 + 1 = 3Output: [2, 3]
Understanding the Visualization
1
Input
Array of words and query ranges
2
Process
Identify words starting/ending with vowels
3
Output
Count of valid words in each query range
Key Takeaway
🎯 Key Insight: Use prefix sums to transform multiple range queries into constant-time lookups
Asked in
Google 15 Amazon 12 Microsoft 8
25.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen