Count Vowel Strings in Ranges — LeetCode 2559 Python Solution
- Problem
- #2559
- Pattern
- Prefix Sum
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- 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".
Python solution
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]Complexity
| Measure | Complexity |
|---|---|
| Time | O(n + m \times \log n) |
| Space | O(n) auxiliary |
Pattern: Prefix Sum
Precompute running totals once so any range query becomes a single subtraction. LeetCode 2559. Count Vowel Strings in Ranges is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Prefix Sum.
The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2559. Count Vowel Strings in Ranges?
- LeetCode 2559. Count Vowel Strings in Ranges is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2559. Count Vowel Strings in Ranges?
- The Python solution on this page runs in O(n + m \times \log n).
- What is the space complexity of LeetCode 2559. Count Vowel Strings in Ranges?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2559. Count Vowel Strings in Ranges cover?
- LeetCode 2559. Count Vowel Strings in Ranges is tagged Array, String and Prefix Sum on LeetCode.