Find Pivot Index

Easy Prefix Sum AI round

nums is a list of whole numbers, which may be negative or zero.

A pivot is a place i where the numbers before it add up to the same as the numbers after it; the number at i itself is in neither sum. Before the first place and after the last there is nothing, and nothing adds up to 0.

Return the first pivot, the one furthest to the left, or -1 if there is none.

Example 1

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

Before place 2 are 3 and 1, which add up to 4; after it are 2 and 2, which add up to 4 as well. Neither place 0 nor place 1 has equal sums.

Example 2

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

No place has the same sum on both sides: the sums before and after each place are 0 and 6, 2 and 9, -1 and 5, 3 and -1, 9 and 0, then 8 and 0.

Example 3

Input: nums = [2,0,0,2]
Output: 1

Constraints

  • 1 ≤ nums.length ≤ 2 × 10⁵
  • -1000 ≤ nums[i] ≤ 1000

Watch the explanation

More Prefix Sum

All Prefix Sum problems