Date: 02-09-2025 Time: 09:00

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 = [ 1,7,3,6,5,6 ] Output: 3 Explanation: The pivot index is 3. Left sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11 Right sum = nums[4] + nums[5] = 5 + 6 = 11

THOUGHT PROCESS:

The most obvious thought process i had was to precompute the left sum and right sum for a given index.

If we want to retrieve this in O(1) we can use an prefixSum arrays

If you take arr = [ 1, 7, 3, 6, 5, 6]

leftPrefixSum: [ 0, 1 , 8, 11 , 17, 22 ] rightPrefixSum: [ 27, 20, 17, 11, 6, 0]

Index: 3 is the same for both

Algorithm:

leftPrefixSum[0] = [0] From: 1n-1 leftPrefixSum[i] = leftPrefixSum[i-1] + arr[i-1]

rightPrefixSum[n-1]=0; n-2 0 rightPrefixSum[i] = rightPrefixSum[i+1] + arr[i+1]

class Solution {
public:
    int pivotIndex(vector<int>& nums) {
        int n = nums.size();
        vector<int> leftPrefixSum(n);
        vector<int> rightPrefixSum(n);
        leftPrefixSum[0]=0;
        rightPrefixSum[n-1]=0;
        for(int i=1;i<n;i++){
           leftPrefixSum[i] = leftPrefixSum[i-1] + nums[i-1];
        }
        for(int i=n-2;i>=0;i--){
            rightPrefixSum[i] = rightPrefixSum[i+1] + nums[i+1];
        }
        int ans = -1;
        for(int i=0;i<n;i++){
            if(leftPrefixSum[i]==rightPrefixSum[i]){
                ans = i;
                break;
            }
        }
        return ans;
    }
};