Find Pivot Index
Easy · Prefix Sums · Array · Prefix Sum
Problem
You are given an integer array nums. An index i is a pivot when the sum of the elements strictly to its left equals the sum of the elements strictly to its right. The element at i itself belongs to neither side, and a side with no elements sums to 0, so index 0 and the last index can be pivots too.
Return the leftmost pivot index, or -1 if no index is a pivot.
Examples
Input: nums = [1, 7, 3, 6, 5, 6] Output: 3
Left of index 3: 1 + 7 + 3 = 11. Right of it: 5 + 6 = 11.
Input: nums = [1, 2, 3] Output: -1
No index has equal sums on both sides.
Input: nums = [2, 1, -1] Output: 0
The left side of index 0 is empty (0), and 1 + (-1) = 0.
Constraints
- 1 <= len(nums) <= 10^4
- -1000 <= nums[i] <= 1000
Approaches
- Prefix sums from both ends — time O(n), space O(n)
Follow-up
Can you report every pivot rather than the first, or, when there is none, the index where the two sides come closest to balancing?
Related problems
Start free on Cariara · Coding problems · System design studio