easy

Find Pivot Index

Find the index where the sum of numbers to the left equals the sum of numbers to the right.

1. Define the problem

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

Inputnums = [1, 7, 3, 6, 5, 6]
Output3

Explanation The sum of the numbers to the left of index 3 (1 + 7 + 3 = 11) equals the sum to the right (5 + 6 = 11).

2. Visualize the solution

Track a running left sum, derive the right sum from the total

Track a running left sum, derive the right sum from the total
Statusinit

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
Step 1 of 3

Steps to visualize

  1. Compute the total sum of the array once.
  2. Walk the array, keeping a running leftSum starting at 0.
  3. At each index, compute rightSum as total - leftSum - numsi.
  4. If leftSum equals rightSum, that index is the pivot — return it.
  5. Otherwise, add numsi onto leftSum and move to the next index.
3. Walk through the code

Walk through the code

Same walkthrough, now with the code. Press Next to move one step and watch which lines run.

Track a running left sum, derive the right sum from the total
Statusinit

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
Step 1 of 3
4. Solution

Solution

solution.tsTypeScript
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)
5. Test cases

Test cases

InputExpectedCovers
nums = [1, 7, 3, 6, 5, 6]3example from the docstring
nums = [1, 2, 3]-1no index balances the two sides
nums = [2, 1, -1]0pivot at the very first index, left sum is 0
nums = [5]0smallest valid input, both sides are empty and equal
nums = [0, 0, 0, 0]0every value zero, leftmost index already balances
nums = [-1, -1, -1, 0, 1, 1]0negative values where the leftmost index is still the pivot