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 in the range li to ri (both inclusive) of words that start and end with a vowel.
Return an arrayans of sizequeries.length , whereans[i]is the answer to theith query.
Note that the vowel letters are 'a', 'e', 'i', 'o', and 'u'.
Examples
Example 1:
| |
Example 2:
| |
Constraints:
1 <= words.length <= 1051 <= words[i].length <= 40words[i]consists only of lowercase English letters.sum(words[i].length) <= 3 * 1051 <= queries.length <= 1050 <= li <= ri < words.length
Solution
We need to determine the number of strings that start and end with a vowel for each given query.
Video explanation
Here is the video explaining this method in detail. Please check it out:
Method 1 - Naive
A direct approach is to iterate through each query and count the valid strings in the specified range.
Here is the approach:
- Iterate over Queries: For each query, iterate through the range of words specified and count how many meet the condition.
- Return Result: Collect answers for all queries and return them.
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n * q), whereqis the number of queries, andnis number of words. As for each query, we might need to scan the entire range specified, leading toO(n * q) - 🧺 Space complexity:
O(1)
Method 2 - Using Prefix Sum
To efficiently solve the problem, we can pre-calculate the number of strings that start and end with a vowel up to each index and store these counts in an array. This technique allows us to answer any query in constant time (O(1)).
Using a prefix sum array, we store the cumulative count of vowel-strings up to any given index i. For any range (i, j), the number of valid strings can be quickly found using the formula:
$$
\text{result} = \text{prefix}[j] - \text{prefix}[i-1]
$$
This approach transforms the problem, enabling us to quickly answer queries about any specified range without repeatedly counting, thus improving efficiency.
Approach
We use a prefix sum array, where each element at index
istores the total number of vowel-strings from the start up to indexi-1.- For eg. for
["aba","bcb","ece","aa","e"]for input array, we check if they start with vowel and end with it ⇨[1, 0, 1, 1, 1](1 means it starts and end with vowel) - and prefix sum will be
[0, 1, 0, 2, 3, 4]
- For eg. for
Then, we run the queries on the prefix sum. For each
query[l, r], our answer will beprefixSum[r + 1] - prefixSum[l].
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n + q) - 🧺 Space complexity:
O(n)for usingprefix sumarray