The problem, in one line. Return the leftmost position where the numbers before it add up to the same as the numbers after it, or -1 if there is none. LeetCode 724.
The tell. A position splits the list in two and you compare the two sums. The left sum is a running total, and the right sum is whatever the grand total leaves over.
The wrong first idea
For every position, add up the left slice and the right slice.
for i in range(len(nums)):
if sum(nums[:i]) == sum(nums[i + 1:]):
return i
Correct, but each position re-adds almost the whole list. With 10,000 numbers that is about 100 million additions.
The invariant
Compute the grand total once. Walk the list keeping left, the sum of everything before the current position. The right side is total - left - nums[i].
[1, 7, 3, 6, 5, 6] total 28
i=2: left 8, right 17. i=3: left 11, right 28 - 11 - 6 = 11. Equal, answer 3.
The sentence that stays true every step: left plus the current number plus the right side always equals the total. So the right side never needs its own pass.
The solution
def pivot_index(nums):
total, left = sum(nums), 0
for i, x in enumerate(nums):
if left == total - left - x: # left sum equals right sum
return i
left += x
return -1
print(pivot_index([1, 7, 3, 6, 5, 6]))
print(pivot_index([1, 2, 3]))
print(pivot_index([2, 1, -1]))
3
-1
0
func pivotIndex(nums []int) int {
total, left := 0, 0
for _, x := range nums {
total += x
}
for i, x := range nums {
if left == total-left-x { // left sum equals right sum
return i
}
left += x
}
return -1
}
Same calls print 3 -1 0.
Complexity
- Time O(n): one pass for the total, one pass to test.
- Space O(1): two numbers.
Traps
- Adding the current number to
leftbefore the test. On[2, 1, -1]the pivot at index 0 is missed and the answer is -1. - Skipping the last index.
[1, -1, 0]has its pivot at 2, because an empty right side sums to 0. Stopping at the second to last position returns -1. - Returning the last match.
[0, 0, 0]has three pivots and the answer is the leftmost, 0.
Next in the ladder
Subarray Sum Equals K asks about every stretch, not one split point. The running total comes back, now stored in a dictionary by value.