Prefix Sums & Suffix Sums
Precompute once, then answer any range sum in O(1).
A sensor logs one reading per second for a day, numbers, and then questions arrive: "what was the total between second and second ?" Looping over every range can cost about additions. One extra array of running totals answers each question with a single subtraction.
What you’ll learn
- Build the prefix array with and , and prove that the inclusive range sum of is .
- Decide which operations allow range queries from prefix arrays (sums, XOR, counts) and which do not (minimum, maximum), and combine prefix and suffix arrays.
- Apply many range additions in each with a difference array, then rebuild the array in one pass.
- Count the subarrays with sum , negative numbers included, with prefix sums and a hash map.
- Recognize prefix-sum problems from their statements and constraints, and avoid their classic bugs.
Precompute once, subtract per query
The brute force answers a range query "the sum of , inclusive" with a loop: additions, so per query and for queries. The waste is plain: every query re-adds numbers that earlier queries already added.
Store running totals once instead. The prefix-sum array has entries,
so is the sum of the first elements, , and is the sum of no elements at all.
By induction on (the base case is ), each entry is the sum of a prefix:
For , both and contain , and that common part cancels:
Seen another way, , and a sum of consecutive differences telescopes. Because , ranges that start at index 0 need no special case.
For the prefix array is . What is the sum of , inclusive?
Show the answer
7
, and indeed . The classic slip is the sum of : it drops .
Code it, then generalize: what can be prefixed?
def build_prefix(a):
P = [0] * (len(a) + 1) # P[0] = 0: the empty prefix
for i, x in enumerate(a):
P[i + 1] = P[i] + x
return P # same as list(itertools.accumulate(a, initial=0))
def range_sum(P, l, r): # inclusive [l, r], 0-indexed
return P[r + 1] - P[l]
P = build_prefix([3, -1, 4, 1, -5, 9, 2, -6])
print(P) # [0, 3, 2, 6, 7, 2, 11, 13, 7]
print(range_sum(P, 2, 5)) # 4 + 1 - 5 + 9 = 9Building takes time and extra space; each query takes time in the worst case. Answering queries costs instead of .
| Operation | How to undo it | Range query from prefix arrays? |
|---|---|---|
| Sum | Subtraction | Yes: |
| XOR | XOR again, since | Yes: |
| Count of a property (letter "a", even values) | Subtraction | Yes: one prefix array per property, e.g. 26 for lowercase letters |
| Product | Division, or a modular inverse | Yes if no factor is zero; otherwise keep a prefix count of zeros beside the product of the nonzero values |
| Minimum, maximum, gcd | None: forgets the larger value | Only prefixes ; general ranges need a sparse table or a segment tree |
With preprocessing into prefix arrays only, which query can you not answer in ?
- The XOR of
- The number of vowels in
- The maximum of
- The sum of squares
Show the answer
C. The maximum of
Maximum has no inverse: knowing and tells you nothing about when the overall maximum lies before . The other three are prefix differences of a group operation.
Suffix arrays: looking both ways
Suffix sums run the other way: and , so is the sum of . Many problems ask each index about everything to its left and everything to its right at once. Precompute both directions and every index sees both sides in .
An equilibrium index has : the elements before it balance the elements after it. In it is index 2, since .
def product_except_self(a):
n = len(a)
out = [1] * n
left = 1
for i in range(n): # out[i] = product of a[0..i-1]
out[i] = left
left *= a[i]
right = 1
for i in range(n - 1, -1, -1): # times the product of a[i+1..n-1]
out[i] *= right
right *= a[i]
return out
print(product_except_self([2, 3, 0, 4])) # [0, 0, 24, 0]The product of all other elements, without division: a prefix product times a suffix product, time and extra space beyond the output. Dividing the total by fails as soon as some .
Think first Bars of heights stand side by side and it rains. Water above bar rises to the lower of the tallest bar on its left and the tallest on its right (both including bar ). How do prefix and suffix maxima compute the total, and what is it?
Let and , one left-to-right and one right-to-left pass. Bar holds . Here , , and the water is . Maximum has no inverse, but this problem only ever asks about whole prefixes and whole suffixes, never a range in the middle. (The two-pointer lesson solves it with extra space.)
Range updates: the difference array
Now flip the workload: many range updates "add to ", and the array is read only at the end. Looping costs per update. A difference array records only where neighboring values change:
Prefix sums of give back . Adding to the whole block changes only two differences: the step up at and the step down after . So an update is and , and one prefix pass at the end rebuilds : for updates.
def apply_range_adds(n, updates):
D = [0] * (n + 1) # one spare slot, so r + 1 never overflows
for l, r, v in updates: # add v to a[l..r], inclusive
D[l] += v
D[r + 1] -= v
a, run = [0] * n, 0
for i in range(n): # one prefix pass rebuilds the array
run += D[i]
a[i] = run
return a
print(apply_range_adds(8, [(1, 4, 5), (3, 6, -2), (0, 2, 1)]))
# [1, 6, 6, 3, 3, -2, -2, 0]Prefix sums and differences undo each other, just as integration and differentiation do. When reads are interleaved with the updates, keep in a Fenwick tree: a range update becomes two point updates and reading becomes a prefix sum, each (see Segment Trees & Fenwick Trees).
Subarrays with sum k: prefix sums meet a hash map
How many subarrays have sum exactly ? The brute force checks all of them. With negative numbers a sliding window fails, because extending a window can make its sum go down as well as up.
Prefix sums turn subarrays into pairs: has sum exactly when with . So scan from left to right and ask how many earlier prefixes equal . A hash map from prefix value to the number of times it has occurred answers that in expected time.
from collections import defaultdict
def count_subarrays(a, k):
seen = defaultdict(int)
seen[0] = 1 # the empty prefix P[0] = 0
prefix = count = 0
for x in a:
prefix += x # prefix = P[j]
count += seen[prefix - k] # earlier i with P[i] = P[j] - k
seen[prefix] += 1
return count
print(count_subarrays([2, -1, 3, -2, 4, -3, 1, 2], 3)) # 4One pass: expected time with a hash map ( worst case with a balanced search tree instead) and space.
Think first For and , the prefix sums are . Find the four pairs with . Which subarray would the code miss if it started with an empty map instead of ?
gives ; gives ; gives ; gives . Without the entry for , the pair is never counted: every subarray that starts at index 0 disappears, and the code returns 3. The Optimal lesson Subarray Sums: Hash Maps & Kadane's Algorithm extends this idea to divisibility, balance and longest-subarray variants.
Recognizing it
Reach for prefix arrays when you see these signals:
- Many range questions on an array that does not change: sums, XORs or counts over , with and up to about to , where is far too slow and fits.
- Many range additions, read only at the end: bookings, schedules, paint-the-fence updates. That is a difference array.
- "How many subarrays have sum (or XOR) , or a sum divisible by ?", especially with negative numbers: prefix values plus a hash map.
- "For every index, combine everything to its left with everything to its right": prefix and suffix arrays.
| Problem (in brief) | Key idea | Cost |
|---|---|---|
| Sums of many ranges of a fixed array | ||
| How often a letter occurs in many substrings | One prefix count per letter | |
| Product of all other elements, no division | Prefix product times suffix product | |
| Apply range increments, then print the array | Difference array, one rebuild pass | |
| Count subarrays with sum , negatives allowed | Count earlier prefixes equal to | expected |
A hotel has rooms and receives bookings, each "rooms through need one extra cleaner tomorrow". After all bookings, you must print the number of cleaners each room needs. Which technique fits best?
- A loop over each booking's rooms
- A difference array with one rebuild pass
- A prefix-sum array rebuilt after every booking
- A hash map of prefix sums
Show the answer
B. A difference array with one rebuild pass
Every booking is a range update and all reads happen at the end: , , then one prefix pass, in total, about simple steps.
#include <cstdio>
#include <vector>
int main() {
int n, q;
if (scanf("%d %d", &n, &q) != 2) return 0;
std::vector<long long> P(n + 1, 0); // P[0] = 0
for (int i = 0; i < n; i++) {
long long x;
scanf("%lld", &x);
P[i + 1] = P[i] + x; // 64-bit: 2e5 values of 1e9 overflow int
}
while (q--) {
int l, r; // 0-indexed, inclusive
scanf("%d %d", &l, &r);
printf("%lld\n", P[r + 1] - P[l]);
}
}The contest version: long long sums and C-style I/O, which is fast enough for queries.
Key takeaways
- With and , the inclusive sum of is : preprocessing, per query.
- Prefix tricks need an inverse: sums, XOR and counts answer any range, while minimum, maximum and gcd answer only prefixes and suffixes.
- Prefix and suffix arrays together give every index "everything to my left" and "everything to my right" in : products of all others, equilibrium indices, trapped rain water.
- A difference array turns each range addition into two point updates; one prefix pass rebuilds the array, in total.
- Subarrays with sum are pairs of prefixes with : one scan with a hash map counts them, negative numbers included.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
has entries with and . Which expression is the sum of , inclusive?
Show the answer
C.
is the sum of and the sum of ; their difference is exactly .
An array of numbers receives operations, each either "set to " or "report the sum of ", in any order. Which structure fits?
- A prefix array, rebuilt after every change
- A Fenwick tree (or segment tree)
- A difference array
- A hash map of prefix sums
Show the answer
B. A Fenwick tree (or segment tree)
Updates and queries are interleaved, so the array is not static. A Fenwick tree handles a point update and a prefix sum in each, about steps per kind of operation.
The difference array of (with ) has and . To add to , inclusive, which entries change?
- and
- all increase by
- and
- and
Show the answer
A. and
Inside the block every neighbor difference is unchanged. The step up happens between and , which is , and the step down between and , which is .
You must count the subarrays with sum exactly , and the array contains negative numbers. Which approach is correct and runs in expected time?
- A sliding window that shrinks while its sum exceeds
- Sort the array, then use two pointers
- Scan prefix sums, counting earlier prefixes equal to in a hash map
- Kadane's algorithm
Show the answer
C. Scan prefix sums, counting earlier prefixes equal to in a hash map
Each subarray is a pair with . Scanning while counting the earlier prefix values in a hash map finds all of them in one pass.
Go deeper
- Difference Arrays & Sweep Lines · Range updates in O(1), interval overlaps and event sweeps.
- 2-D Prefix Sums & Inclusion–Exclusion · Summed-area tables, rectangle queries and higher dimensions.
- Subarray Sums: Hash Maps & Kadane’s Algorithm · Counting subarrays with sum k, and the maximum subarray in one pass.
Further reading
- A. Laaksonen, Competitive Programmer's Handbook (2018), chapter 9, "Range queries" (free online).
- G. E. Blelloch, "Prefix sums and their applications," Technical Report CMU-CS-90-190, Carnegie Mellon University (1990).
- P. M. Fenwick, "A new data structure for cumulative frequency tables," Software: Practice and Experience 24(3) (1994), 327–336.