2559: Count-Vowel-Strings-in-Ranges
Medium
table of contents
Immediately, when I finished reading the question, I thought of prefix sums.
In my algorithm, I iterated through the words in words
and initalised a prefix sum array, pSum
.
Using pSum
, I am then able to return ans
in
O(n)
time, with each ans[i]
being calculated
in O(1)
.
(if an array looked like: [a, b, c, d]
,
then its prefix sum would look like:
[a, a+b, a+b+c, a+b+c+d]
,
meaning if we wanted to find the sum of all elements between
e.g. index 1
and 2
inclusive,
we can simply do the operation pSum[2]-pSum[0]
to achieve
the same result without iterating through the
array)
code
class Solution {
public:
<int> vowelStrings(vector<string>& words, vector<vector<int>>& queries) {
vector<int> pSum (words.size(), 0);
vector<char> vowels = {'a', 'e', 'i', 'o', 'u'};
unordered_set int counter = 0;
for (int i = 0; i < pSum.size(); ++i) {
if (vowels.count(words[i][0]) && vowels.count(words[i][words[i].size()-1]))
++counter;
[i] = counter;
pSum}
<int> ans (queries.size());
vectorint temp;
for (int i = 0; i < queries.size(); ++i) {
= pSum[queries[i][1]];
temp if (queries[i][0] > 0) {
-= pSum[queries[i][0]-1];
temp }
[i] = temp;
ans}
return ans;
}
};