Find Pivot Index
Given an array of integers nums, find the leftmost pivot index — the index where the sum of every number to its left equals the sum of every number to its right . If no such index exists, return -1. The total sum is fixed, so the right-hand sum at any index is always total - leftSum - numsi , which means the right side never needs to be re-summed.
Constraints
- 1 ≤ nums.length ≤ 104
- -1000 ≤ numsi ≤ 1000
Example
nums = [1, 7, 3, 6, 5, 6]3Explanation The sum of the numbers to the left of index 3 (1 + 7 + 3 = 11) equals the sum to the right (5 + 6 = 11).
Track a running left sum, derive the right sum from the total
total=28. index=0: leftSum=0, rightSum=28-0-1=27. Not equal.
What happens in this step
total = 1+7+3+6+5+6 = 28 i=0: leftSum=0 rightSum = total - leftSum - nums[0] = 28 - 0 - 1 = 27 0 !== 27 → not the pivot leftSum += nums[0] → leftSum = 1
Steps to visualize
- Compute the total sum of the array once.
- Walk the array, keeping a running leftSum starting at 0.
- At each index, compute rightSum as total - leftSum - numsi.
- If leftSum equals rightSum, that index is the pivot — return it.
- Otherwise, add numsi onto leftSum and move to the next index.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
total=28. index=0: leftSum=0, rightSum=28-0-1=27. Not equal.
What happens in this step
total = 1+7+3+6+5+6 = 28 i=0: leftSum=0 rightSum = total - leftSum - nums[0] = 28 - 0 - 1 = 27 0 !== 27 → not the pivot leftSum += nums[0] → leftSum = 1
Solution
function pivotIndex(nums) {
const total = nums.reduce((sum, value) => sum + value, 0);
let leftSum = 0;
for (let i = 0; i < nums.length; i++) {
const rightSum = total - leftSum - nums[i];
if (leftSum === rightSum) {
return i;
}
leftSum += nums[i];
}
return -1;
}- Time
- O(n)
- Space
- O(1)
Test cases
| Input | Expected | Covers |
|---|---|---|
nums = [1, 7, 3, 6, 5, 6] | 3 | example from the docstring |
nums = [1, 2, 3] | -1 | no index balances the two sides |
nums = [2, 1, -1] | 0 | pivot at the very first index, left sum is 0 |
nums = [5] | 0 | smallest valid input, both sides are empty and equal |
nums = [0, 0, 0, 0] | 0 | every value zero, leftmost index already balances |
nums = [-1, -1, -1, 0, 1, 1] | 0 | negative values where the leftmost index is still the pivot |