Skip to content

Prefix sums: any range total in one subtraction

Working knowledgeConcept

Asking for the sum of a range again and again means a loop each time, over values you have already added. Add everything up once, keeping the running totals, and every range sum after that is one subtraction.

01 Many range questions, one array

Say you have daily sales for a year and a dashboard that asks for totals: this week, last month, the 30 days before a launch. The direct way loops over the range for every question. With q questions over ranges of up to n days, that is O(n·q) additions, and most of them repeat work done for an earlier question.

Loop for every query
def range_sum(a, left, right):
total = 0
for i in range(left, right + 1): # up to n additions
total += a[i]
return total
Subtract two totals
# prefix built once: prefix[i] = a[0] + ... + a[i-1]
def range_sum(prefix, left, right):
return prefix[right + 1] - prefix[left] # 1 subtraction

The right-hand version needs a table built in advance, but only once: O(n) time and n + 1 numbers of memory. After that each query is O(1), whatever the length of the range.

02 Build the running totals once

A prefix sum array stores, at index i, the total of the first i values. Each cell is the previous cell plus one more value, so the whole table takes one pass.

Running totals of [3, 1, 4, 1, 5, 9, 2, 6]
Step 1 of 10
a · 8 values
30
11
42
13
54
95
26
67
prefix · 9 cells, prefix[i] = sum of first i
0
1
2
3
4
5
6
7
8
  • value added now
  • total so far
  • cell just filled
  • not filled yet

You have a and an empty prefix with one more cell than a. Cell prefix[i] will hold the sum of the first i values.

0 additions

03 A range total is one subtraction

The total up to the end of a range includes everything before the range too. The total up to the start of the range is exactly that extra part. Take one from the other and only the range is left.

The sum of a[2..5] is prefix[6] − prefix[2] = 23 − 4 = 19
a · the range 2..5
30
11
l42
13
54
r95
26
67
prefix · two cells read
00
31
l42
83
94
145
r+1236
257
318
  • the range asked for
  • the two cells you read

prefix[6] is 3 + 1 + 4 + 1 + 5 + 9. prefix[2] is 3 + 1. Subtracting removes the part before the range and leaves 4 + 1 + 5 + 9 = 19.

Loop per queryO(n) each10,000 queries over a 1,000,000-value array can mean up to 10 billion additions.
Prefix sumsO(1) eachOne pass of 1,000,000 additions to build, then 10,000 subtractions.

04 Why the extra zero at the front

You could store prefix[i] as the sum up to and including a[i], with no leading zero. Then a range that starts at index 0 needs a special case, because there is no cell before it to subtract. The leading 0 is that missing cell.

Ranges on a = [3, 1, 4, 1, 5, 9, 2, 6], with prefix = [0, 3, 4, 8, 9, 14, 23, 25, 31]
RangeFormulaResult
a[2..5]prefix[6] - prefix[2]23 - 4 = 19
a[0..7]prefix[8] - prefix[0]31 - 0 = 31
a[0..0]prefix[1] - prefix[0]3 - 0 = 3
a[3..3]prefix[4] - prefix[3]9 - 8 = 1

The usual bug is reading prefix[right] instead of prefix[right + 1]. With the leading zero, prefix is shifted one place right of a: the sum through a[right] lives at prefix[right + 1]. Test a one-value range such as a[3..3]; it must return a[3].

05 See it in code

Here is the whole thing. build_prefix runs once; range_sum runs for every question.

range_sums.py
def build_prefix(a):
prefix = [0] * (len(a) + 1) # prefix[i] = sum of the first i values
for i, x in enumerate(a):
prefix[i + 1] = prefix[i] + x
return prefix
def range_sum(prefix, left, right):
"""Sum of a[left..right], both ends included."""
return prefix[right + 1] - prefix[left]
a = [3, 1, 4, 1, 5, 9, 2, 6]
prefix = build_prefix(a)
print(prefix)
print(range_sum(prefix, 2, 5)) # 4 + 1 + 5 + 9
print(range_sum(prefix, 0, 7)) # the whole array
print(range_sum(prefix, 3, 3)) # one value
Text
$ python3 range_sums.py
[0, 3, 4, 8, 9, 14, 23, 25, 31]
19
31
1

Python can build the same table with itertools.accumulate(a, initial=0), which also gives the leading zero.

06 Prefix sums plus a hash map

Some questions do not give you the range. How many subarrays sum to `k`? A subarray a[i..j] sums to k exactly when prefix[j + 1] − prefix[i] = k, that is, when an earlier prefix equals the current one minus k. So walk once, keep a running sum, and count how often each prefix sum has appeared in a hash map.

Subarrays of [2, 1, −1, 3, −2, 3] that sum to 3
Step 1 of 8
Count 0
nums · k = 3
20
11
-12
33
-24
35
prefix sum → times seen
Empty
  • value read now
  • earlier prefix that fits
  • prefix just recorded

Count the subarrays of nums that sum to 3. The map of prefix sums seen so far is empty.

0 running sum
count_k.py
def count_subarrays(nums, k):
seen = {0: 1} # prefix sum -> how many times it has appeared
running = 0
count = 0
for x in nums:
running += x
count += seen.get(running - k, 0) # earlier prefixes that leave k
seen[running] = seen.get(running, 0) + 1
return count
print(count_subarrays([2, 1, -1, 3, -2, 3], 3))
print(count_subarrays([1, 1, 1], 2))
Text
$ python3 count_k.py
6
2

This works with negative numbers, where a sliding window does not: a window assumes that growing the range only raises the sum. Prefix sums assume nothing about the values, only that you can subtract.

07 The same trick with other operations

Subtraction is what makes ranges work: it undoes the part before the range. Any operation with a cheap undo gets the same trick. Operations without one need a different tool.

Which running totals can answer a range query
OperationUndoRange in O(1)?
SumsubtractYes
XORXOR again (x ^ x = 0)Yes
Count of matchessubtractYes, store a running count
ProductdivideOnly with no zeros; dividing by 0 fails
Max or minnoneNo: use a sparse table or segment tree

Product of Array Except Self sidesteps the zero problem: it multiplies a prefix product from the left by a suffix product from the right, so nothing is ever divided.

The idea also grows a dimension. A 2D prefix table stores the sum of the rectangle from the top-left corner, and any rectangle sum is four lookups: P[r2+1][c2+1] − P[r1][c2+1] − P[r2+1][c1] + P[r1][c1].

08 When prefix sums are the wrong tool

a[3] = 10The array changesOne update shifts every prefix after it, so fixing the table is O(n). With many updates and many queries, use a Fenwick tree or segment tree: both do update and range sum in O(log n).
int[] prefix = new int[n + 1];Overflow in fixed-size integersTotals grow much bigger than the values. In Java or C++, a running sum of a million values near 2,000,000,000 overflows int; use long. Python integers do not overflow.
prefix[right] - prefix[left]Off by oneWith a leading zero the end of the range is right + 1. Drop the + 1 and every answer misses its last value.
seen[running] += 1 # before the lookupStoring before looking upIn the count-to-k loop, recording the current prefix first lets it pair with itself when k = 0, counting an empty subarray. Look up first, then record.

09 Check yourself

Question

With prefix = [0, 3, 4, 8, 9, 14, 23, 25, 31], what is the sum of a[1..4]?

Question

Why does the count-to-k map start with {0: 1}?

Question

An array gets 1,000 updates mixed with 1,000 range queries. What happens to plain prefix sums?

10 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?