Count Vowel Strings in Ranges - Prefix Sum [JS]

Description 

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 in pSum[right]

n = number of wordsm = 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

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]