Skip to main content

724 - Find Pivot Index

Difficulty: Easy | Pattern: Prefix Sum | Company tags: Amazon, Google, Bloomberg

Problem Statement

Given an array of integers nums, calculate the pivot index of this array.

The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the right of the index.

If the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array.

Return the leftmost pivot index. If no such index exists, return -1.

Example 1:

Input: nums = [1,7,3,6,5,6]
Output: 3
Explanation: left_sum=1+7+3=11, right_sum=5+6=11

Example 2:

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

Example 3:

Input: nums = [2,1,-1]
Output: 0 (left_sum=0, right_sum=1+(-1)=0)

Algorithm Flow

Solution: Running Sum — O(n), O(1)

Key insight: left_sum == total - left_sum - nums[i]2 × left_sum + nums[i] == total

def pivotIndex(nums: list[int]) -> int:
total = sum(nums)
left_sum = 0

for i, n in enumerate(nums):
# right_sum = total - left_sum - n
if left_sum == total - left_sum - n:
return i
left_sum += n

return -1

Dry Run

nums = [1,7,3,6,5,6], total=28

inleft_sumright = 28-left_sum-nmatch?
01027No
17120No
23817No
361111Yes → return 3

3

Edge Cases

  • Single element → always a pivot (both sides sum to 0)
  • Leftmost: i=0 → left_sum=0; right_sum=total-nums[0]; if equal → return 0
  • All negative numbers → still works (same math)

Complexity

  • Time: O(n) — one pass for total + one pass for pivot
  • Space: O(1)