Mental model
Think of a car's odometer. To know how far you drove between two stops you do not add up every
road segment; you subtract the two odometer readings. A prefix array is an odometer for an
array: prefix[i] is the total of everything before position i. Any stretch is then the
difference of two readings.
A difference array runs the idea backwards. Instead of storing values, it stores how much each value differs from the one before. Adding 5 to a whole stretch changes only two differences: the step up where the stretch starts and the step down just after it ends.
Building the prefix array
prefix = array of n + 1 zeros # prefix[0] = 0: the empty sum
for i in 0 .. n-1:
prefix[i + 1] = prefix[i] + values[i]
So prefix[i] = values[0] + … + values[i − 1]: the sum of the first i values. For
values = [3, 1, 4, 1, 5, 9, 2, 6] that is [0, 3, 4, 8, 9, 14, 23, 25, 31].
The extra cell is deliberate. With n + 1 cells, the formula below works for every range,
including ranges that start at index 0, with no if. In the lab's 3D view each prefix[i] sits
on the boundary just left of values[i], which makes the formula visible: a range is fenced by
two boundaries.
Answering a range sum
sum(values[from..to]) = prefix[to + 1] - prefix[from] # inclusive range
Why it holds: prefix[to + 1] is the sum of values[0..to], and prefix[from] is the sum of
values[0..from − 1]. Subtracting removes the shared beginning and leaves exactly
values[from..to]. In the example, the sum of values[2..5] is prefix[6] − prefix[2] = 23 − 4 = 19, and it costs two reads whether the range holds one value or a million.
Prefix sums work with negative values too (the running total just goes down as well as up), and they need no ordering of any kind. They do need a static array: changing one value invalidates every prefix after it, an O(n) rebuild. For arrays that change between queries, a Fenwick tree or segment tree gives O(log n) updates and queries.
Difference arrays: many range updates
Now the opposite workload: apply u updates of the form "add delta to values[from..to]", and
only look at the array afterwards. Doing each update directly costs up to n writes, O(n·u).
diff = array of n + 1 zeros # one spare cell
for each update (from, to, delta):
diff[from] += delta # the change starts here
diff[to + 1] -= delta # and stops after `to`
running = 0
for i in 0 .. n-1:
running += diff[i]
result[i] = values[i] + running
Why it holds: after the loop, running at index i is diff[0] + … + diff[i], a prefix sum
of the difference array. An update (from, to, delta) contributes +delta to that sum for every
i ≥ from and cancels out with −delta for every i ≥ to + 1. So it adds delta exactly for
from ≤ i ≤ to, and updates simply add up. Each update costs two writes no matter how long its
range, and one O(n) pass applies them all.
The spare cell diff[n] exists so that an update ending at the last index has somewhere to write
its end marker; it is never read (see the Update to the end preset).
Complexity
| Task | Direct | With the technique | Extra space |
|---|---|---|---|
| q range-sum queries on a static array | O(n·q) worst case | O(n) build + O(1) per query | n + 1 cells |
| u range updates, then read the array | O(n·u) worst case | O(1) per update + one O(n) pass | n + 1 cells |
| Point update between queries | O(1) | O(n) rebuild (use a Fenwick tree instead) | — |
Both techniques trade memory for time: n + 1 extra cells, usually 64-bit ones.
Where prefix sums show up
- Prefix sums with a hash map. "How many subarrays sum to exactly k?" becomes "how many earlier
prefixes equal
prefix[i] − k?" One pass with a map of prefix counts gives O(n), negative values included. Practise it in How many stretches add up to k?. - Balance points. An index where the left and right sides weigh the same satisfies
prefix[i] = total − prefix[i + 1]: Where do both sides weigh the same?. - Prefix products. The same idea with multiplication, from both ends, avoids division: Every product but your own.
- 2D prefix sums.
P[r][c]holds the sum of the rectangle above and left of(r, c); any rectangle sum is thenP[r2+1][c2+1] − P[r1][c2+1] − P[r2+1][c1] + P[r1][c1](inclusion–exclusion).
Language notes
Overflow. The prefix of n 32-bit values can be up to n times larger than any value, so the
listings store prefixes and differences as long (C#, Java) or std::int64_t (C++). In C# and
Java an int prefix would wrap around silently; in C++ signed overflow is undefined behaviour.
Python integers have arbitrary precision. 64 bits is enough for any array of 32-bit values that
fits in memory: even 2³¹ values of magnitude 2³¹ sum to at most 2⁶², below the 2⁶³ limit.
Built-ins.
| Language | Running totals | Notes |
|---|---|---|
| C# | no direct built-in; a loop, or values.Aggregate(...) for a single total |
write the loop for a prefix array |
| Python | list(itertools.accumulate(values, initial=0)) |
initial=0 (Python 3.8+) gives exactly the n + 1 layout |
| Java | Arrays.parallelPrefix(long[] array, Long::sum) |
in place, on a copy you made as long[]; no leading 0 |
| C++ | std::partial_sum, std::inclusive_scan (C++17) |
write into a std::vector<std::int64_t> so the sums are 64-bit; no leading 0 |
The C++ test checks the listing against std::partial_sum, and the Python test against
itertools.accumulate.
The teaching implementation
Build / build_prefix, RangeSum / range_sum and ApplyRangeAdds / apply_range_adds are
written the same way in all four languages. Each language reads one shared fixture (empty array,
one value, whole-array and single-cell ranges, negatives, nested and cancelling updates, extremes)
and compares its results with summing and updating every range directly on 1,000 random arrays.
Ranges are inclusive and must satisfy 0 ≤ from ≤ to < n; the listings document this
precondition rather than checking it, and the lab rejects bad ranges before running.
Common mistakes
- A prefix array of length n. Then ranges starting at 0 need a special case, and
prefix[to] − prefix[from − 1]reads index −1. Use n + 1 cells. - Mixing inclusive and exclusive ends.
prefix[to + 1] − prefix[from]is for the inclusive range[from, to]; for a half-open[from, to)it isprefix[to] − prefix[from]. - Forgetting the end marker in a difference array, so the update runs to the end of the array.
- No spare cell, so an update ending at
n − 1writes out of bounds. - Reusing a prefix array after the values changed.
Edge cases
- Empty array: the prefix array is
[0]; there are no valid ranges. - One value:
prefix = [0, v]; the only range sum isv. - An update with
delta = 0, or two updates that cancel: the array is unchanged. - Ranges covering the whole array:
prefix[n] − prefix[0], the total.
Worked practice
1. Build the prefix array of [2, −1, 3] and compute the sum of values[1..2].
Answer
prefix = [0, 2, 1, 4]. Sum of values[1..2] = prefix[3] − prefix[1] = 4 − 2 = 2 (−1 + 3).
2. Apply "add 3 to [1, 4]" and "add −1 to [0, 2]" to eight zeros with a difference array.
Answer
diff[1] += 3, diff[5] −= 3, diff[0] −= 1, diff[3] += 1 gives
diff = [−1, 3, 0, 1, 0, −3, 0, 0, 0]. Running sums: [−1, 2, 2, 3, 3, 0, 0, 0].
3. How many subarrays of [1, 2, 3] sum to 3, using prefixes?
Answer
Prefixes [0, 1, 3, 6]. Count pairs i < j with prefix[j] − prefix[i] = 3: (0, 2) gives
[1, 2] and (2, 3) gives [3]. Two subarrays.
4. Why does a difference array not help if you must read the array after every update?
Answer
Reading a value needs the running sum up to that index, which is O(n) to recompute after each update. The difference array wins only when updates are batched and read once at the end. For interleaved updates and reads, use a Fenwick tree or a segment tree.
Summary
prefix[i]= sum of the firstivalues; n + 1 cells withprefix[0] = 0.- Range sum
[from, to]=prefix[to + 1] − prefix[from]: O(1) after an O(n) build. - Difference array: two writes per range update, one O(n) running sum to apply them all.
- The two are inverses: prefix-summing a difference array gives back the values.
- Store sums in 64 bits in C#, Java and C++.