2559. Count Vowel Strings in Ranges - Explanation

Problem Link



1. Brute Force

class Solution:
    def vowelStrings(self, words: List[str], queries: List[List[int]]) -> List[int]:
        vowels = set("aeiou")
        res = []

        for start, end in queries:
            cnt = 0
            for i in range(start, end + 1):
                if words[i][0] in vowels and words[i][-1] in vowels:
                    cnt += 1
            res.append(cnt)

        return res

Time & Space Complexity

  • Time complexity: O(nm)O(n * m)
  • Space complexity:
    • O(1)O(1) extra space.
    • O(m)O(m) space for the output list.

Where nn is the number of words, and mm is the number of queries.


2. Prefix Sum + Hash Set

class Solution:
    def vowelStrings(self, words: List[str], queries: List[List[int]]) -> List[int]:
        vowel_set = set("aeiou")
        prefix_cnt = [0] * (len(words) + 1)
        prev = 0

        for i, w in enumerate(words):
            if w[0] in vowel_set and w[-1] in vowel_set:
                prev += 1
            prefix_cnt[i + 1] = prev

        res = [0] * len(queries)
        for i, q in enumerate(queries):
            l, r = q
            res[i] = prefix_cnt[r + 1] - prefix_cnt[l]

        return res

Time & Space Complexity

  • Time complexity: O(n+m)O(n + m)
  • Space complexity:
    • O(n)O(n) extra space.
    • O(m)O(m) space for the output list.

Where nn is the number of words, and mm is the number of queries.


3. Prefix Sum + Bitmask

class Solution:
    def vowelStrings(self, words: List[str], queries: List[List[int]]) -> List[int]:
        vowels = sum(1 << (ord(c) - ord('a')) for c in "aeiou")
        prefix = [0]
        for w in words:
            prefix.append(prefix[-1])
            if (1 << (ord(w[0]) - ord('a'))) & vowels and (1 << (ord(w[-1]) - ord('a'))) & vowels:
                prefix[-1] += 1
        return [prefix[r + 1] - prefix[l] for l, r in queries]

Time & Space Complexity

  • Time complexity: O(n+m)O(n + m)
  • Space complexity:
    • O(n)O(n) extra space.
    • O(m)O(m) space for the output list.

Where nn is the number of words, and mm is the number of queries.