The problem, in one line. Build once from a list that never changes, then answer many queries asking for the sum between two positions. LeetCode 303.
The tell. One fixed list and many range-sum questions. When the same data is asked about again and again, pay once up front for running totals.
The wrong first idea
Add up the slice for every query.
def sum_range(self, left, right):
return sum(self.nums[left:right + 1])
Each query walks the range. With 10,000 numbers and 10,000 queries that is up to 100 million additions, and the list never changed between them.
The invariant
Build p where p[i] is the sum of the first i numbers, with p[0] = 0. A range is then two readings and a subtraction.
nums = [-2, 0, 3, -5, 2, -1] p = [0, -2, -2, 1, -4, -2, -3]
sum from 0 to 2 = p[3] - p[0] = 1 - 0 = 1
The sentence that stays true: p[i] holds the sum of everything before position i, so the difference of two readings is exactly what lies between them.
The solution
class NumArray:
def __init__(self, nums):
self.p = [0] # p[i] = sum of the first i numbers
for x in nums:
self.p.append(self.p[-1] + x)
def sum_range(self, left, right):
return self.p[right + 1] - self.p[left]
na = NumArray([-2, 0, 3, -5, 2, -1])
print(na.sum_range(0, 2))
print(na.sum_range(2, 5))
print(na.sum_range(0, 5))
1
-1
-3
type NumArray struct{ p []int }
func NewNumArray(nums []int) *NumArray {
p := make([]int, len(nums)+1) // p[i] = sum of the first i numbers
for i, x := range nums {
p[i+1] = p[i] + x
}
return &NumArray{p}
}
func (a *NumArray) SumRange(left, right int) int { return a.p[right+1] - a.p[left] }
Same calls print 1 -1 -3.
Complexity
- Time O(n) to build and O(1) per query: one subtraction.
- Space O(n): one extra total per number, plus the leading zero.
Traps
- Storing the sum through each index, then reading
p[left - 1]. Atleft = 0Python readsp[-1], the grand total, and the first call answers 4 instead of 1. - Reading
p[right] - p[left]. With the leading zero, the first call becomes -2 and the last number of the range is lost. - Rebuilding the totals inside each query. It passes the three calls and times out on 10,000 queries over 10,000 numbers.
Next in the ladder
Find Pivot Index needs only one split point, so a single running total and the grand total are enough and the table goes away.