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 Ranges INPUT words array: 0 1 2 3 4 "aba" "bcb" "ece" "aa" "e" Vowel start+end Not valid Vowels: a, e, i, o, u queries: [0, 2] [1, 4] Query 1 idx 0 to 2 Query 2 idx 1 to 4 Valid words: indices 0,2,3,4 (4 words start+end with vowel) ALGORITHM STEPS 1 Build Prefix Sum Count valid words up to each index prefix[i] = count of valid words [0..i-1] 0 1 1 2 3 4 i=0 1 2 3 4 5 2 Query Formula ans = prefix[r+1] - prefix[l] 3 Process Query [0,2] prefix[3] - prefix[0] = 2 - 0 = 2 Range [0,2]: "aba","bcb","ece" Valid: "aba","ece" = 2 4 Process Query [1,4] prefix[5] - prefix[1] = 4 - 1 = 3 Range [1,4]: "bcb","ece","aa","e" Valid: "ece","aa","e" = 3 FINAL RESULT Output Array [2, 3] Answer Breakdown: Query [0, 2] --> ans[0] = 2 Words: "aba", "bcb", "ece" Valid vowel strings: 2 Query [1, 4] --> ans[1] = 3 Words: "bcb", "ece", "aa", "e" Valid vowel strings: 3 Time: O(n + q) Space: O(n) Key Insight: Use prefix sum to precompute cumulative count of valid vowel strings. Each query becomes O(1) using formula: count(l, r) = prefix[r+1] - prefix[l]. This avoids recomputing for each query. A string is valid if its first AND last character are vowels (a, e, i, o, u). TutorialsPoint - Count Vowel Strings in Ranges | Prefix Sum Approach
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