Leetcode 2559: Count Vowel Strings in Ranges

grid47
grid47
Exploring patterns and algorithms
Feb 25, 2024 6 min read

Given an array of strings words and a list of queries, each query asks to count the number of strings in the specified range that start and end with a vowel. The vowels are ‘a’, ’e’, ‘i’, ‘o’, and ‘u’.
Problem
Approach
Steps
Complexity
Input: An array of strings `words` and a list of queries where each query specifies a range of indices in `words`.
Example: words = ["aba", "bcb", "ace", "aa", "e"], queries = [[0,2],[1,4],[1,1]]
Constraints:
• 1 <= words.length <= 10^5
• 1 <= words[i].length <= 40
• sum(words[i].length) <= 3 * 10^5
• 1 <= queries.length <= 10^5
• 0 <= li <= ri < words.length
Output: Return an array of integers where each element is the count of valid strings (those starting and ending with a vowel) in the given range for each query.
Example: [2, 3, 0]
Constraints:
Goal: To efficiently compute the number of valid strings in the range for each query, we preprocess the input to allow fast queries.
Steps:
• 1. Iterate over the words and determine if they start and end with a vowel.
• 2. Maintain a prefix sum array to quickly compute the count of valid words in any given range.
• 3. For each query, compute the difference between the prefix sums at the range boundaries.
Goal: The solution must handle large input sizes efficiently, with up to 100,000 words and 100,000 queries.
Steps:
• Handle up to 100,000 queries efficiently.
• The length of each word is at most 40, and the total sum of lengths does not exceed 300,000.
Assumptions:
• Words consist only of lowercase English letters.
• Each query is valid, i.e., 0 <= li <= ri < words.length.
Input: words = ["aba", "bcb", "ace", "aa", "e"], queries = [[0,2],[1,4],[1,1]]
Explanation: The valid strings are 'aba', 'ace', 'aa', and 'e'. The answers to the queries are 2, 3, and 0 respectively.

Input: words = ["a", "e", "i"], queries = [[0,2],[0,1],[2,2]]
Explanation: All the strings satisfy the condition of starting and ending with vowels. Hence, the answers to the queries are 3, 2, and 1 respectively.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus