Home
DSA Patterns
Prefix Sum
Find Pivot Index
Find Pivot Index
Find the leftmost index whose left and right sums are equal, using the array total and one running left sum instead of a second prefix array.
Problem Understanding
Find Pivot Index (LeetCode 724): given an integer array nums, return the leftmost index where the sum of the elements strictly to its left equals the sum of the elements strictly to its right. If no such index exists, return -1. The values may be negative.
Examples: [1, 7, 3, 6, 5, 6] → 3 (1 + 7 + 3 = 11 = 5 + 6); [1, 2, 3] → -1; [2, 1, -1] → 0.
The Intuition: The Right Side Is What Is Left Over
Adding up both sides at every index is O(n²). A prefix sum array would answer the left side in O(1), but you do not need the array at all.
- Sum everything once. Call it
total. - Keep a running
left. It holds the sum of everything before i. - Read off the right side. Whatever is not left of i and not at i is right of it:
right = total - left - nums[i].
It is the same idea as Introduction to Prefix Sums, kept to a single number. Product of Array Except Self uses the same left-side, right-side split with products.
Interactive Walkthrough
RIGHT = TOTAL − LEFT − nums[i]
SUM THE ARRAY
nums
0
1
2
3
4
5
Total
28
Left
0
Right
:
Answer
:
Sum the whole array once: total = 28. Nothing is left of index 0 yet, so left = 0
Next
i = 0: left = 0, right = 28 − 0 − 1 = 27. Not equal
nums
The outlined cells are already summed into left; the filled cell is i. Try Index 0 to see a pivot with nothing on its left, and Example 2 for an array with no pivot.
Dry Run Table
Input: nums = [1, 7, 3, 6, 5, 6], so total = 28.
| i | nums[i] | left | right = 28 − left − nums[i] | Equal? |
|---|---|---|---|---|
| 0 | 1 | 0 | 27 | no |
| 1 | 7 | 1 | 20 | no |
| 2 | 3 | 8 | 17 | no |
| 3 | 6 | 11 | 11 | yes |
Answer: 3.
The Solution Template
One pass to sum the array, one pass to find the pivot. Compare before adding nums[i] to left, so the pivot itself is in neither sum.
Find Pivot Index Code
1var pivotIndex = function(nums) {2 const total = nums.reduce((sum, x) => sum + x, 0);3 let left = 0;4 for (let i = 0; i < nums.length; i++) {5 if (left === total - left - nums[i]) {6 return i;7 }8 left += nums[i];9 }10 return -1;11};
Edge Cases & Common Mistakes
- Adding nums[i] before comparing: then left includes the pivot and the check is off by one element.
- Pivot at index 0: the left sum is 0, so
[2, 1, -1]returns 0. - Several pivots:
[0, 0, 0]balances everywhere; return the leftmost, which the left-to-right scan does naturally. - Single element: both sides are empty, so index 0 is the pivot.
- Two pointers do not work: with negative values, moving the side with the smaller sum can skip the answer.
Summary
Sum the array, then scan once with a running left sum. At each index the right sum is total - left - nums[i]; return the first index where the two are equal, or -1. O(n) time, O(1) extra space.
More practice: DSA interview questions with answers · patterns cheat sheet
