Count Vowel Strings in Ranges - Prefix Sum [JS]
Solution: Prefix Sum
Calculate the prefix sum: pSum[i] = the number of words in range [0, i] that start and end with vowels.
For each query [left, right]
, the answer = pSum[right] - pSum[left - 1]
pSum[right] = words that start and end with vowels in range [0, right]
- Then we subtract
pSum[left - 1]
since those counts were also included inpSum[right]
n = number of words
, m = number of queries
Time Complexity: O(n + m)
Space Complexity: O(n + m)
var vowelStrings = function(words, queries) {
let n = words.length;
let pSum = Array(n).fill(0);
for (let i = 0; i < n; i++) {
if (i > 0) pSum[i] = pSum[i - 1];
if (isVowel(words[i][0]) && isVowel(words[i][words[i].length - 1])) {
pSum[i]++;
}
}
let res = [];
for (let [l, r] of queries) {
if (l === 0) res.push(pSum[r]);
else res.push(pSum[r] - pSum[l - 1]);
}
return res;
};
function isVowel(char) {
return ['a', 'e', 'i', 'o', 'u'].includes(char);
}
Comments
Post a Comment