Count Vowel Strings in Ranges - Problem
Imagine you're working with a text analysis system that needs to quickly answer queries about specific word patterns. You have an array of words and need to efficiently handle multiple range queries.
Given a 0-indexed array of strings words and a 2D array of integers queries, your task is to count how many words in each specified range start and end with a vowel.
Each query queries[i] = [li, ri] asks: "How many strings at indices from li to ri (both inclusive) start and end with a vowel?"
Return an array ans where ans[i] is the answer to the i-th query.
Note: Vowels are 'a', 'e', 'i', 'o', and 'u' (case-sensitive).
Input & Output
example_1.py โ Basic Case
$
Input:
words = ["aba","bcb","ece","aa","e"], queries = [[0,2],[1,4],[1,1]]
โบ
Output:
[2,3,0]
๐ก Note:
Query [0,2]: "aba"(โ), "bcb"(โ), "ece"(โ) โ count = 2. Query [1,4]: "bcb"(โ), "ece"(โ), "aa"(โ), "e"(โ) โ count = 3. Query [1,1]: "bcb"(โ) โ count = 0.
example_2.py โ Single Character
$
Input:
words = ["a","e","i"], queries = [[0,2],[0,1]]
โบ
Output:
[3,2]
๐ก Note:
All single vowel characters start and end with vowels. Query [0,2]: all 3 words qualify. Query [0,1]: first 2 words qualify.
example_3.py โ No Matches
$
Input:
words = ["hello","world","coding"], queries = [[0,2],[1,2]]
โบ
Output:
[0,0]
๐ก Note:
None of the words start and end with vowels: "hello"(consonant-vowel), "world"(consonant-consonant), "coding"(consonant-consonant).
Constraints
- 1 โค words.length โค 105
- 1 โค words[i].length โค 40
- words[i] consists only of lowercase English letters
- 1 โค queries.length โค 3 ร 105
- queries[i] = [li, ri]
- 0 โค li โค ri < words.length
Visualization
Tap to expand
Understanding the Visualization
1
Scan and Mark
Go through each word, check if it starts and ends with vowels
2
Build Prefix
Create cumulative sum: prefix[i] = total count from start to position i-1
3
Range Query
For range [l,r]: answer = prefix[r+1] - prefix[l]
4
Instant Result
Each query answered in O(1) time using simple arithmetic
Key Takeaway
๐ฏ Key Insight: Prefix sums transform O(N) range queries into O(1) arithmetic operations, making this approach optimal for multiple queries.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code