Find Pivot Index
Find the leftmost index where the sum on its left equals the sum on its right, using one running sum.
The problem
You get an integer array nums. A pivot index is a position where the sum of all numbers strictly to its left equals the sum of all numbers strictly to its right; a side with no numbers sums to 0. Return the leftmost pivot index, or -1 if there is none.
Input nums = [2, 5, 1, 4, 3]
Output 2
Left of index 2: 2 + 5 = 7. Right of it: 4 + 3 = 7.
Input nums = [3, -3, 8]
Output 2
Left of index 2: 3 + (-3) = 0, and the right side is empty, which also sums to 0.
How to spot the pattern
- You compare the sum before a position with the sum after it.
- Recomputing both sums for every position would repeat the same additions over and over.
The idea
If you know the total of the whole array and the running sum left of everything before index i, then the right side is simply total - left - nums[i]. So add up the array once, then walk left to right while keeping left up to date. The first index where left equals the right side is the answer.
Brute force: For each index, add up both sides from scratch, which takes O(n^2) time.
Step by step
- 1Add up the whole array to get
total. - 2Walk through the indices with
left = 0, the sum of everything before the current index. - 3Compute
right = total - left - nums[i]. - 4If
left == right, returni; otherwise addnums[i]toleftand move on. - 5If no index matches, return -1.
See the pattern move
The prefix sums pattern on a small example. Step through it, or press play.
Code
class Solution:
def pivotIndex(self, nums: List[int]) -> int:
total = sum(nums)
left = 0 # sum of everything before index i
for i, num in enumerate(nums):
right = total - left - num
if left == right:
return i
left += num
return -1Complexity
Time
O(n)
Space
O(1)
Two passes over the array, one for the total and one for the walk, with two running sums.
Watch out for
- Adding
nums[i]toleftbefore comparing, which counts the pivot itself as part of the left side. - Stopping early once
leftgrows past the right side: with negative numbers the two sums can still meet later. - Forgetting that index 0 and the last index can be pivots, because an empty side sums to 0.
Follow-up questions
How would you answer many "sum of nums[i..j]" questions quickly?
Build a prefix sum array once, then every range sum is prefix[j + 1] - prefix[i] in O(1). That is Range Sum Query - Immutable.
What changes if all the numbers are positive?
The left sum only grows and the right sum only shrinks, so there is at most one pivot, and you can stop as soon as left passes right.
In Hinglish
Pehle poora total nikalo. Phir chalte chalte left sum rakho; right sum bas total - left - nums[i] hai.