Prefix Sum
Read a little, play a little. No scary maths, and no rush.
Pay once, query forever
"Sum of elements 3 through 7?" — asked a thousand times on a million-element array. Re-adding each time costs O(n) per query. A prefix sum array precomputes running totals once, so every range question becomes one subtraction:
pref = [0]
for x in a:
pref.append(pref[-1] + x)
# sum of a[l..r] = pref[r+1] - pref[l]
pref[i] means "sum of the first i elements," so the window [l, r] is just two lookups apart. Build O(n), query O(1) — the classic space-for-time trade, and it extends to 2D grids (summed-area tables, the trick behind fast image filters).
The idea with real numbers
Take a = [3, 1, 4, 1, 5]. The prefix array is pref = [0, 3, 4, 8, 9, 14]: each entry is the total of everything before it, starting from an empty sum of 0.
What is the sum of a[1..3], that is 1 + 4 + 1? The formula gives pref[4] − pref[1] = 9 − 3 = 6, which matches. The leading 0 is what makes the formula work for ranges that start at index 0, with no special case.
The famous upgrade: subarray sum equals K
Count subarrays summing to k — brute force is O(n²). The insight: a subarray (i..j] sums to k exactly when pref[j] − pref[i] = k, i.e. we've seen prefix value cur − k before. Count frequencies as you sweep:
def subarray_k(a, k):
from collections import Counter
freq, cur, ans = Counter({0: 1}), 0, 0
for x in a:
cur += x
ans += freq[cur - k] # how many starts complete a k-sum here?
freq[cur] += 1
return ans
The Counter({0: 1}) seed handles subarrays starting at index 0 — the detail interviewers check for.
A trace of the counting trick
subarray_k([1, 2, 3], k=3), starting with freq = {0: 1}:
- x = 1: cur = 1. Look up 1 − 3 = −2: not seen. Record cur = 1.
- x = 2: cur = 3. Look up 3 − 3 = 0: seen once, so one subarray ends here, namely [1, 2]. Record cur = 3.
- x = 3: cur = 6. Look up 6 − 3 = 3: seen once, so another subarray ends here, namely [3]. Record cur = 6.
Answer: 2. Without the {0: 1} seed, the step at x = 2 would have found nothing and the answer [1, 2], which starts at index 0, would have been missed.
Variants worth recognizing
- Difference arrays. To add a value v to every element in a range many times, record
diff[l] += vanddiff[r + 1] -= v, then take the prefix sum once at the end. Range updates become O(1) each. - Prefix and suffix products. "Product of the array except self" multiplies the product of everything to the left by the product of everything to the right, avoiding division.
- Other running totals. The same idea works with XOR, counts of a category, or any operation that can be undone, which is what makes the subtraction step possible.
- Running balances. A bank statement's balance column is a prefix sum of transactions, so the net change between any two dates is one subtraction.
Remember this
- Repeated range sums → prefix array. Subarray-sum counting → prefix frequencies + hash map.
- One subtraction per query is the whole point; say the tradeoff aloud.
Check your understanding
5 questions · first-try answers earn the most XP
My notes
Saved in this browser. Highlight a line above and save it, or write it in your own words.
Nothing saved yet. Your highlights will live here.
References
Finished reading?
Ticking it here also ticks the chapter in the sidebar, the section count and your streak — it is all one number.
Related chapters
Practice this pattern elsewhere
More problems to practise on external judges. Both links open the site home rather than a specific set, so you can pick problems for this pattern.
Spotted a mistake or want a topic covered? Report an issue