← Course home

Problem-solving methods · Lesson 42 of 52

Prefix sums

Answer range-sum queries and count target-sum subarrays from cumulative totals.

Full lessonAbout 9 min

You will learn to derive half-open range sums and count target subarrays using prior prefix frequencies.

Recommended first: Arrays and Python sequence costs.

On this page 6 sections

The idea

PrefixSum on 1, 2, 3, 4 answers range_sum(1, 3) with 5.

A prefix sum array stores the total of every item up to each index. The library PrefixSum on 1, 2, 3, 4 builds those totals once. range_sum(start, end) returns the sum of values[start:end], end exclusive. range_sum(1, 3) is 2 + 3, which is 5. The formula is total[end] minus total[start]. The item at start is included and the item at end is not, matching a Python slice. Any later range on the same array is then a subtraction. Counting subarrays that sum to a target uses the same totals. As you walk the array. A map from a previous prefix. To how many times it occurred tells you how many earlier starts would make the current prefix hit the target.

A worked trace

StepStateWhat changed
Prefixsum = 1range_sum from 0 to 1 returns 1.
Prefixsum = 3range_sum from 0 to 2 returns 3.
Prefixsum = 10range_sum from 0 to 4 returns 10.
Slicesum = 5range_sum from 1 to 3 returns 5, which is 2 + 3.

Why it is correct

total[0] is 0, the sum of an empty prefix. total[i + 1] is total[i] plus values[i]. By induction, total[end] is the sum of the first end items. Subtracting total[start] removes the items before the slice and leaves the slice. The half-open interval is why you do not add or drop an endpoint by hand. A target count is the same identity. If the current prefix minus a previous prefix equals the target, the slice between them sums to the target. The frequency map counts how many such previous prefixes exist.

A common mistake

The end index is exclusive. Including it adds the value at that index.

What it costs

Building the totals is linear time and linear extra memory. Each range query is constant time. n separate queries are therefore linear after the build, not quadratic. The frequency-map walk is linear expected time with a dictionary. Use prefix sums when the array does not change. A point update would force you to rebuild, which is why a later lesson brings a Fenwick tree. The build is Θ(n) time and uses Θ(n) extra memory.

Run it

python
from bitsandbytes.patterns.arrays import PrefixSumprint(PrefixSum([1, 2, 3, 4]).range_sum(1, 3))# prints: 5 

Practice and next step

Open Backtracking search next. Backtracking searches a tree of choices and undoes each choice before the next sibling.

Implementation and tests Optional reference

Library code 1

  • bitsandbytes.patterns.arrays

Use these references to compare the explanation with repository code and tests. A test link means it imports a lesson symbol; it does not by itself claim complete behavior coverage.

Step-by-step trace

A half-open range sum

PrefixSum on 1, 2, 3, 4 answers range_sum(1, 3) with 5, the sum of values[1:3].

sum
1

State

  1. 01chosen

range_sum from 0 to 1 returns 1.

Practice with feedback

Check your understanding

Try each checkpoint before revealing the feedback. Ask for a hint when you need one. Answers and hints stay in this browser when local storage is available.

1Prefix totals exist for 1, 2, 3, 4. range_sum(1, 3) uses which formula?
2You know how many earlier prefixes equal the current prefix minus the target. What does that frequency count?

Progress is never sent to an account or synced to another device. If local storage is blocked, choices last only until you leave this page.