Prefix Sum Flashcards

(2 cards)

1
Q

Find Pivot Index

Given an array of integers nums, calculate the pivot index of this array.

The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index’s right.

If the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array.

Return the leftmost pivot index. If no such index exists, return -1.

Input: nums = [2,1,-1]
Output: 0
Explanation:
The pivot index is 0.
Left sum = 0 (no elements to the left of index 0)
Right sum = nums[1] + nums[2] = 1 + -1 = 0

A

sum to left of index = cumulativeSum[index-1]
sum to right of index = cumulativeSum[arr.length] - cumulativeSum[index]

Add in some painful index manipulation:

    if (nums==null || nums.length==0) return -1;
    int[] cumulativeSum = new int[nums.length+1];
    for(int index=0; index < nums.length; index++)
        cumulativeSum[index+1] = cumulativeSum[index] + nums[index];
    for(int index=0; index < nums.length; index++) {
        int sumToLeft = cumulativeSum[index];
        int sumToRight = cumulativeSum[nums.length] - cumulativeSum[index+1];
        if (sumToLeft == sumToRight)
            return index;
    }
    return -1;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Count Vowel Strings in Ranges

You are given a 0-indexed array of strings words and a 2D array of integers queries.

Each query queries[i] = [li, ri] asks us to find the number of strings present at the indices ranging from li to ri (both inclusive) of words that start and end with a vowel.

Return an array ans of size queries.length, where ans[i] is the answer to the ith query.

Input: words = [“aba”,”bcb”,”ece”,”aa”,”e”], queries = [[0,2],[1,4],[1,1]]
Output: [2,3,0]
Explanation: The strings starting and ending with a vowel are “aba”, “ece”, “aa” and “e”.
The answer to the query [0,2] is 2 (strings “aba” and “ece”).
to query [1,4] is 3 (strings “ece”, “aa”, “e”).
to query [1,1] is 0.
We return [2,3,0].

A

int[] cumulative = new int[words.length+1];
Set<Character> vowels = Set.of('a', 'e', 'i', 'o', 'u');
for(int index=1; index <= words.length; index++) {
cumulative[index] = cumulative[index-1];
if (words[index-1]!= null && words[index-1].length()!=0 &&
vowels.contains(words[index-1].charAt(0)) && vowels.contains(words[index-1].charAt(words[index-1].length()-1))) {
cumulative[index]++;
}
}
int[] result = new int[queries.length];
for(int index=0; index<queries.length; index++) {
int start = queries[index][0];
int end = queries[index][1];
result[index] = cumulative[end+1] - cumulative[start];
}
return result;</Character>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly