Command Palette

Search for a command to run...

Problem 5.2 · Prefix SumEasy

Find Pivot Index

What it teaches: Use the total to get the right-side sum for free: right = total − left − nums[i].

Practise it on judges as “Find Pivot Index”.

The problem

Return the leftmost index where the sum of all numbers strictly to its left equals the sum of all numbers strictly to its right. If none exists, return -1. The left sum at index 0 is 0, and so is the right sum at the last index.

Example 1

Input: nums = [1, 7, 3, 6, 5, 6]
Output: 3

Left: 1 + 7 + 3 = 11. Right: 5 + 6 = 11.

Example 2

Input: nums = [1, 2, 3]
Output: -1

Example 3

Input: nums = [2, 1, -1]
Output: 0

Left of index 0 is empty (0); right is 1 + (−1) = 0.

Constraints

  • 1 ≤ nums.length ≤ 10⁴
  • −1000 ≤ nums[i] ≤ 1000

Pattern clues in the wording

  • → Compare the sum on the left with the sum on the right of each index
  • → Both sides are ranges: prefix sums

These clues point to Prefix Sum: Store running totals so the sum of any range is one subtraction: prefix[r + 1] - prefix[l].

Stuck? Take one hint at a time

Solution.java · starter
class Solution {
    public int pivotIndex(int[] nums) {
        return -1;
    }
}

Write your solution locally or in your editor for now. The in-browser runner (Java first, then Python, C++ and more) will run these tests right here.

Test cases

#InputExpected
1
nums = [1,7,3,6,5,6]
3
2
nums = [1,2,3]
-1
3
nums = [2,1,-1]
0

+ 1 hidden test the code runner will check

From slow to fast

Approaches

1

Optimal: running left sum and the total

Time O(n) Space O(1)

Compute the total. Walk left to right keeping left. At index i, right = total − left − nums[i]. If they're equal, return i. Then add nums[i] to left.

▶ Dry run: Left sum versus right sumnums = [1, 7, 3, 6, 5, 6] (total 28)
1
0
↑i
7
1
3
2
6
3
5
4
6
5

State(vars)

left = 0right = 27

Step 1/4i = 0: right = 28 − 0 − 1 = 27. Not equal.

Approach 1
class Solution {
    public int pivotIndex(int[] nums) {
        int total = 0;
        for (int x : nums) total += x;
        int left = 0;
        for (int i = 0; i < nums.length; i++) {
            if (left == total - left - nums[i]) return i;
            left += nums[i];
        }
        return -1;
    }
}

Verdict: Two passes, no prefix array needed.

Before you submit

Edge cases and common mistakes

Test these inputs

  • Pivot at index 0
  • Pivot at the last index
  • No pivot
  • Negative numbers

Mistakes people make

  • Adding nums[i] to left before comparing (then the pivot's own value is counted on the left).

Interview

Follow-up questions

How would you find all pivot indexes?