Prefix Sums
Remember totals up to each position so range sums can be answered quickly.
prefix sum, range sum, array, cumulativeTotals along a path
Imagine writing down how many steps you have walked at each stop. To find the steps between two stops, subtract the earlier total from the later total.
A prefix is the beginning of a sequence. A prefix-sum list stores the total before each position, including zero before the first item.
Why use it and where it helps
If the same unchanging row receives many range-sum questions, computing totals once can make each later question quick. This is useful for summaries such as total rainfall over different spans of days. Building the totals takes work and memory, so a single small query may not benefit.
Follow an example
For values [3, -1, 4, 2], write a zero first, then add each value:
values: 3 -1 4 2
prefix: 0 3 2 6 8
index: 0 1 2 3 4
The sum from index 1 up to, but not including, index 3 is 6 - 3 = 3.
That matches -1 + 4. The same convention lets an empty range have sum zero.
See the reasoning
Follow the example one step at a time
Build prefix totals and answer a range-sum question. This is a prepared teaching demonstration, not live code execution.
Start with zero
values: [3, -1, 4, 2] prefix: [0]
The sum before the first item is zero.
Python illustration
def prefix_sums(numbers):
totals = [0]
for number in numbers:
totals.append(totals[-1] + number)
return totals
def range_sum(totals, start, end):
if not 0 <= start <= end < len(totals):
raise ValueError("invalid range")
return totals[end] - totals[start]
totals = prefix_sums([3, -1, 4, 2])
print(totals)
print(range_sum(totals, 1, 3))
print(range_sum(totals, 2, 2))
Prepared output — not live execution:
[0, 3, 2, 6, 8]
3
0
The range includes start and excludes end. The function expects a prefix
list produced by prefix_sums and integer indices; it raises ValueError for
out-of-range or reversed indices. Negative values are fine.
Time, space, and common mistakes
Building totals for n items takes O(n) time and O(n) extra space. Each valid
range query then takes O(1) time. The totals are a snapshot: changing an input
item does not update them automatically. Take care not to confuse an input
index with the prefix index after that item.
Reflect on the concept
Four fixed questions to reinforce the reasoning. Answers are not saved or scored.
