Find Pivot Index

Given an array, find the leftmost index where the sum of all elements to its left equals the sum of all elements to its right. Return -1 if no such index exists.

EasyRecommendedPrefix Sum
Solve This Problem

Video Solution

Video coming soon

We're producing a video walkthrough — check back soon.

Problem Overview

Given an array, find the leftmost index where the sum of all elements to its left equals the sum of all elements to its right. Return -1 if no such index exists.

Why solve this?

The cleanest possible bridge from plain traversal into prefix-sum thinking: it looks like it needs two separate prefix and suffix arrays, but the total sum alone is enough to derive the right-hand side on the fly.

Pattern Recognition

Whenever a problem compares a running left-hand quantity against a right-hand quantity that's 'everything else', check whether the right-hand side can be derived from the total minus what's already been tracked, instead of building a second array.

Prerequisites

  • Running Sum of 1d Array — the same running-total idea, used here as a comparison rather than an output.

Hints

  1. You don't need a separate array for the right-hand sums — a running left sum and the array's total sum are enough.
  2. At index i, the right sum is exactly total - leftSum - nums[i] (leftSum doesn't yet include nums[i]).
  3. Walk left to right, comparing leftSum to the derived right sum before adding nums[i] into leftSum for the next index.

Approach

Compute the total sum of the array once. Then walk the array left to right with a running leftSum, initialized to 0. At each index i, the sum of everything to the right of i is total - leftSum - nums[i] (leftSum only accounts for elements strictly before i). If leftSum equals that derived right sum, index i is a valid pivot — since the scan moves left to right, the first match found is automatically the leftmost one. If no index matches by the end of the scan, add nums[i] to leftSum and continue; if the loop finishes with no match, return -1.

Code

Solution.java
class Solution {
    public int pivotIndex(int[] nums) {
        int total = 0;
        for (int num : nums) total += num;
        int leftSum = 0;
        for (int i = 0; i < nums.length; i++) {
            int rightSum = total - leftSum - nums[i];
            if (leftSum == rightSum) return i;
            leftSum += nums[i];
        }
        return -1;
    }
}
Time: O(n)Space: O(1)

Related Problems

Back to Arrays