Skip to content

Find Pivot Index

LeetCode

01 · Question

Given an array of integers nums, return the pivot index where the sum of the numbers to the left equals the sum of the numbers to the right.

02 · Analysis

Compute total once. At index i, the right sum is total-left-nums[i]. Compare before adding nums[i] to left, so the pivot belongs to neither side. Return the first match; return -1 if none exists. Empty sides have sum zero. Time O(n), auxiliary space O(1).

03 · Solution

Reference solution

1def pivotIndex(nums: List[int]) -> int:
2 total = sum(nums)
3 left = 0
4
5 for i, x in enumerate(nums):
6 if left == total - left - x:
7 return i
8 left += x
9
10 return -1