Count Vowel Strings in Ranges Problem
Description
LeetCode Problem 2559.
You are given a 0-indexed array of strings words and a 2D array of integers queries.
Each query queries[i] = [l_i, r_i] asks us to find the number of strings present at the indices ranging from l_i to r_i (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 i^th query.
Note that the vowel letters are 'a', 'e', 'i', 'o', and 'u'.
Example 1:
Input: words = ["aba","bcb","ece","aa","e"], queries = [[0,2],[1,4],[1,1]]
Output: [2,3,0]
Explanation: The strings starting and ending with a vowel are "aba", "ece", "aa" and "e".
The answer to the query [0,2] is 2 (strings "aba" and "ece").
to query [1,4] is 3 (strings "ece", "aa", "e").
to query [1,1] is 0.
We return [2,3,0].
Example 2:
Input: words = ["a","e","i"], queries = [[0,2],[0,1],[2,2]]
Output: [3,2,1]
Explanation: Every string satisfies the conditions, so we return [3,2,1].
Constraints:
1 <= words.length <= 10^51 <= words[i].length <= 40words[i]consists only of lowercase English letters.sum(words[i].length) <= 3 * 10^51 <= queries.length <= 10^50 <= l_i <= r_i < words.length
Solution
Approach: Prefix Counts
Mark each word that starts and ends with a vowel. Let s[i] be the number of marked words among the first i words. The answer to a query (l, r) is then s[r + 1] - s[l], answered in constant time. (A sorted list of marked indices with two binary searches works as well.)
Complexity: O(n + q) time and O(n) extra space, where n is the number of words and q the number of queries.
from bisect import bisect_left, bisect_right
class Solution:
def vowelStrings(self, words: List[str], queries: List[List[int]]) -> List[int]:
vowels = set("aeiou")
nums = [i for i, w in enumerate(words) if w[0] in vowels and w[-1] in vowels]
return [bisect_right(nums, r) - bisect_left(nums, l) for l, r in queries]