Count Vowel Strings in Ranges

medium prefix sum range query string

Problem

You are given a 0-indexed array of strings words and a list of queries. Each query [l, r] asks how many strings at indices l through r (inclusive) both start and end with a vowel (a, e, i, o, u). Return an array with the answer to every query.

Inputwords = ["aba","bcb","ece","aa","e"], queries = [[0,2],[1,4],[1,1]]
Output[2,3,0]
Vowel-bounded words are "aba", "ece", "aa", "e". Query [0,2] → 2, [1,4] → 3, [1,1] → 0.

def vowel_strings(words, queries):
    vowels = set("aeiou")
    n = len(words)
    prefix = [0] * (n + 1)
    for i, w in enumerate(words):
        ok = w[0] in vowels and w[-1] in vowels
        prefix[i + 1] = prefix[i] + (1 if ok else 0)
    ans = []
    for l, r in queries:
        ans.append(prefix[r + 1] - prefix[l])
    return ans
function vowelStrings(words, queries) {
  const vowels = new Set(["a", "e", "i", "o", "u"]);
  const n = words.length;
  const prefix = new Array(n + 1).fill(0);
  for (let i = 0; i < n; i++) {
    const w = words[i];
    const ok = vowels.has(w[0]) && vowels.has(w[w.length - 1]);
    prefix[i + 1] = prefix[i] + (ok ? 1 : 0);
  }
  return queries.map(function (q) {
    return prefix[q[1] + 1] - prefix[q[0]];
  });
}
int[] vowelStrings(String[] words, int[][] queries) {
    String vowels = "aeiou";
    int n = words.length;
    int[] prefix = new int[n + 1];
    for (int i = 0; i < n; i++) {
        String w = words[i];
        boolean ok = vowels.indexOf(w.charAt(0)) >= 0
                  && vowels.indexOf(w.charAt(w.length() - 1)) >= 0;
        prefix[i + 1] = prefix[i] + (ok ? 1 : 0);
    }
    int[] ans = new int[queries.length];
    for (int i = 0; i < queries.length; i++)
        ans[i] = prefix[queries[i][1] + 1] - prefix[queries[i][0]];
    return ans;
}
vector<int> vowelStrings(vector<string>& words, vector<vector<int>>& queries) {
    string vowels = "aeiou";
    int n = words.size();
    vector<int> prefix(n + 1, 0);
    for (int i = 0; i < n; i++) {
        string& w = words[i];
        bool ok = vowels.find(w.front()) != string::npos
               && vowels.find(w.back()) != string::npos;
        prefix[i + 1] = prefix[i] + (ok ? 1 : 0);
    }
    vector<int> ans;
    for (auto& q : queries)
        ans.push_back(prefix[q[1] + 1] - prefix[q[0]]);
    return ans;
}
Time: O(n + q) Space: O(n)