Running totals: any range sum in one step
🌍 In real life. A car's odometer doesn't record each trip; it keeps one running total of kilometres. To know how far you drove between Comilla and Chattogram, you don't add up every kilometre: you read the odometer at both places and subtract. Your bank statement works the same way: each line shows the balance so far, and the money spent between the 5th and the 20th is one balance minus another.
Keep running totals once, and every "how much between here and there?" becomes one subtraction.
The idea in one sentence: build prefix, where prefix[k] is the sum of the first k numbers; then the sum of nums[i:j] is prefix[j] - prefix[i].
Its words:
- prefix sum: a running total;
prefix[0] = 0,prefix[k + 1] = prefix[k] + nums[k] - range sum: the sum of a stretch
nums[i:j](from i up to, but not including, j, like a slice)
How it works, step by step:
- start with
prefix = [0] - for each number, append
prefix[-1] + x: n additions, once - for each question "sum of nums[i:j]?", answer
prefix[j] - prefix[i]
Watch the towers rise, one addition each, then each range read off as one tower minus another:
Why it is correct. prefix[j] adds up nums[0:j] and prefix[i] adds up nums[0:i]. The first i numbers are in both, so they cancel, leaving exactly nums[i:j].
What it costs, worked out. Building is n additions, once. Then each range is one subtraction, however long. With n numbers and q questions:
- adding each range from scratch: up to n additions per question, O(n × q): 10,000 numbers and 10,000 questions is up to 100 million additions
- prefix sums: 10,000 additions plus 10,000 subtractions, O(n + q)
The price is O(n) extra memory for the prefix list. And it only works while the numbers don't change: changing one number means rebuilding everything after it.
from itertools import accumulate
nums = [3, 1, 4, 1, 5]
prefix = [0]
for x in nums:
prefix.append(prefix[-1] + x)
print(prefix)
def range_sum(prefix, i, j):
return prefix[j] - prefix[i] # sum(nums[i:j])
print(range_sum(prefix, 1, 4), sum(nums[1:4]))
print([0] + list(accumulate(nums))) # the built-in wayMistakes and edge cases.
- forgetting the leading 0: without it, ranges that start at 0 need a special case, and every index is off by one
- mixing up ends: with
prefix[j] - prefix[i], j is not included, just likenums[i:j]; if a question says "from i to j inclusive", useprefix[j + 1] - prefix[i] - an empty range (i == j) is 0, which the formula gives for free
Quiz
What does this print?
nums = [2, 5, 1, 4] prefix = [0] for x in nums: prefix.append(prefix[-1] + x) print(prefix)With prefix = [0, 2, 7, 8, 12], what is the sum of nums[1:3]? What does this print?
prefix = [0, 2, 7, 8, 12] print(prefix[3] - prefix[1])Why does prefix start with 0?
- So prefix[j] − prefix[i] works for ranges starting at 0 too, and prefix[k] is the sum of the first k numbers
- Python lists must start with 0
- To make the list sorted
n numbers, q range questions. What does the prefix-sum way cost?
- O(n + q)
- O(n × q)
- O(q)
This should give the sum of nums[i:j], but it gives wrong sums (or crashes) for most ranges. Which line is wrong?
def range_sums(nums, queries): prefix = [] for x in nums: prefix.append((prefix[-1] if prefix else 0) + x) return [prefix[j] - prefix[i] for i, j in queries]
Coding tasks
Write
running_totals(nums): the prefix sums ofnums, starting with 0, so the result is one longer thannums.Write
range_sums(nums, queries)in O(n + q): for each (i, j) inqueries, the sum ofnums[i:j], as a list. Build the prefix sums once.