Find Pivot Index
Difficulty: Easy · Pattern: Prefix Sum · LeetCode #724
The pivot index is an index where the sum of all elements strictly to its left equals the sum of all elements strictly to its right (an empty side sums to 0). Return the leftmost pivot index, or −1 if none exists.
Examples
text
nums = [2, 3, -1, 8, 4] → 3 (2+3−1 = 4 = 4)
nums = [1, 2, 3] → −1
nums = [5, 1, -1] → 0 (left is empty = 0, right = 1 − 1 = 0)Hints
- If you know the total sum and the sum to the left of i, what's the sum to the right?
- right = total − left − nums[i].
Approach
Compute total once. Scan with a running left sum: at index i, the right sum is total − left − nums[i]. If they're equal, return i; otherwise add nums[i] to left. One pass after the total, O(1) space.
Complexity
Time: O(n). Space: O(1).
Python solution
def pivotIndex(nums):
total, left = sum(nums), 0
for i, x in enumerate(nums):
if left == total - left - x:
return i
left += x
return -1JavaScript solution
function pivotIndex(nums) {
const total = nums.reduce((a, b) => a + b, 0);
let left = 0;
for (let i = 0; i < nums.length; i++) {
if (left === total - left - nums[i]) return i;
left += nums[i];
}
return -1;
}