Prefix Sum — add once, answer forever
Cumulative sums, range queries, the hash-map counting trick, 2D summed-area tables and difference arrays — from first principles to interview-ready patterns.
AChapter introduction
Prerequisites
You should be comfortable with Python lists and 0-based indexing, for loops, basic Big-O notation (what O(n) and O(1) mean), and Python dictionaries. No prior knowledge of trees or advanced mathematics is needed; the only formula you must remember fits on one line.
Learning objectives
After completing this chapter you will be able to:
- Define a prefix sum array formally and informally, and explain the role of the leading zero (the sentinel).
- Answer any contiguous range-sum query in constant time using P[R+1] − P[L], and prove why it is correct.
- Analyse the build, query and update costs, and explain exactly when prefix sums stop being the right tool.
- Combine prefix sums with a hash map to count or find subarrays with a given property in linear time.
- Extend the idea to two dimensions (summed-area tables / integral images) using inclusion–exclusion.
- Use the inverse operation — the difference array — to apply many range updates in O(1) each.
- Recognise prefix-sum patterns in interview problems, and know the next structures to reach for (Fenwick tree, segment tree, parallel scan).
BFundamental understanding
What is a prefix sum?
Take a list of numbers. Walk through it from left to right, keeping a running total, and write down the total after each step. The list of totals you wrote down is the list of prefix sums (also called cumulative sums or running totals). For the natural numbers 1, 2, 3, 4, 5, 6 the prefix sums are 1, 3, 6, 10, 15, 21 — the triangular numbers. [8]
In algorithm design we almost always use the exclusive, sentinel-padded form, which has one extra slot at the front:
So P[i] is the sum of the first i elements, and P has length n+1. This is the convention used by CMU’s 15-451 lecture notes, Swarthmore’s competitive programming notes and the USACO Guide. [2][13][3]
Inclusive versus exclusive scans
The two forms differ only in whether element i is included in output i. An inclusive scan gives yi = a0 + … + ai; an exclusive scan gives yi = a0 + … + ai−1 and starts with the identity (0 for addition). They convert into each other by shifting by one position, and real libraries ship both — C++ has std::inclusive_scan and std::exclusive_scan, MPI has MPI_Scan and MPI_Exscan. [8][12] The padded array P above is simply the exclusive scan with the grand total appended at the end.
Why does this concept exist?
Many questions about a sequence are really questions about a contiguous stretch of it: total sales between day 30 and day 90, number of errors logged between two timestamps, how many 1-bits lie in a window. Answering each such question by looping over the stretch costs time proportional to its length. When the data does not change but the questions keep coming, that repeated work is wasted: the same additions are performed again and again. Prefix sums do the additions once and store them so that every future query reuses them. [2]
A little history
The running total is ancient, but the prefix sum as a named algorithmic building block has a well-documented modern history. Parallel prefix methods were studied for binary adder circuits by Ofman (1962) and Khrapchenko (1967); Ladner and Fischer (1980) gave general parallel prefix computation; Hillis and Steele (1986) published a short-span data-parallel algorithm; and Blelloch’s 1990 work made “scan” a primitive of data-parallel programming. [8][1] In computer graphics, Franklin Crow introduced the two-dimensional version — the summed-area table — for texture mapping at SIGGRAPH 1984, and Viola and Jones later popularised it in computer vision as the integral image. [10][9] Fenwick (1994) introduced the binary indexed tree to keep prefix sums under updates. [8][7]
Fundamental principles
Three ideas carry the whole chapter:
- Precomputation trades space for time. Store n+1 extra numbers and queries drop from linear to constant time. [2]
- Subtraction cancels a shared prefix. The sum of A[L..R] is “everything up to R” minus “everything before L”. This works because addition has an inverse (subtraction). Operators without an inverse — like
max— still have prefix scans, but cannot answer arbitrary ranges this way. [1][7] - Prefix sums and differences are inverse operations. Taking adjacent differences of P gives back A; taking prefix sums of a difference array gives back the original — the discrete analogue of integration and differentiation. [14]
CThe problem statement
The Static Range Sum Query problem
| Component | Specification |
|---|---|
| Input | An array A of n numbers that does not change, and q queries, each a pair (L, R) with 0 ≤ L ≤ R < n. |
| Output | For each query, the value A[L] + A[L+1] + … + A[R]. |
| Typical constraints | Competitive-programming versions such as CSES “Static Range Sum Queries” use n, q up to 2·105 with values up to 109, so totals exceed 32-bit range. [19] |
| Key assumption | No element is modified between queries (a static array). [2] |
Why the naive approach is inefficient
The obvious solution loops over positions L to R for each query. That costs Θ(R − L + 1), which is O(n) in the worst case, so q queries cost O(n·q). [2] With n = q = 2·105 that is up to 4·1010 additions — far too slow. In Python, sum(A[L:R+1]) looks like one operation but is not: slicing a list of k items costs O(k) and summing costs another O(k). [16]
Limitations of other approaches
Precomputing every answer in an n × n table gives O(1) queries but needs Θ(n2) memory and time — 4·1010 cells for the constraint above. A segment tree answers queries in O(log n) and also supports updates, but it is more code and slower per query than necessary when the array never changes. [2]
How prefix sums improve the solution
Build P in one O(n) pass, then answer each query with P[R+1] − P[L] in O(1). Total: O(n + q) time and O(n) extra space. For a static array this is essentially optimal, since just reading the input already takes Ω(n + q). [2][3]
DVisual whiteboard explanations
All diagrams in this chapter use one colour language. Learn it once and every picture reads the same way:
- Start the green row with the sentinel
P[0] = 0— the sum of zero elements. - For each
i, carry the previous total (purple arrow) and add the blue value directly above-left (A[i]). - The highlighted step shows
P[6] = P[5] + A[5] = 14 + 9 = 23.
P is offset by one slot relative to A; P[i] summarises the first i elements, so len(P) = n + 1 and P[n] is the grand total (31).
- Both arrays are ordinary contiguous lists;
Ahas indices 0…7 andPhas indices 0…8. - A brace under
Ashows which elements a single green number summarises:P[3]coversA[0..2],P[6]coversA[0..5],P[8]covers everything. P[0]covers nothing — the empty prefix — which is why it is 0.
P is a contiguous array, P[k] is read in O(1) by address arithmetic, exactly like any list access.
- Query
L = 2, R = 5asks for4 + 1 + 5 + 9. - The long green brace
P[6] = 23coversA[0..5]; the short red braceP[2] = 4coversA[0..1]. - Their overlap
A[0..1]cancels, leaving exactly the yellow range:23 − 4 = 19.
R − L + 1. [2]
- Before: the naive method moves a pointer across every cell in the range — 4 additions for
(2,5), 8 for(0,7), and the overlapping cells are re-added for every query. - After: the prefix method touches exactly two green cells per query, no matter how wide the range is.
EInteractive lab
The labs below are fully working. Change the inputs, step forwards and backwards, and watch the state panel. Labs 2–4 preview techniques explained in detail in Section F; feel free to return to them after reading it.
FInternal working
F.1 Memory representation
In Python, both A and P are list objects: contiguous arrays of references to integer objects, so indexing P[k] is O(1). [16] Python integers have unlimited precision, so the running total can never overflow — a real difference from C, Java or NumPy, where a 64-bit accumulator wraps around silently. [17][6] In a low-level language you would choose a wide accumulator type (for example 64-bit) because n · max|A[i]| can exceed the element type’s range even when every element fits. [19]
F.2 Execution flow of the build
- Allocate
Pof length n+1 filled with zeros.P[0] = 0is now set. - For i = 0, 1, …, n−1: read
P[i](the total so far), readA[i], writeP[i+1] = P[i] + A[i]. - Stop.
P[n]holds the sum of the whole array.
Each iteration reads two values and writes one, in strictly increasing memory order — a single sequential pass that is cache-friendly. The loop has a dependency chain (step i+1 needs step i), which is why the parallel versions in Section N need a cleverer algorithm. [12]
F.3 Execution flow of a query
- Validate 0 ≤ L ≤ R < n.
- Read
P[R+1](sum ofA[0..R]) andP[L](sum ofA[0..L−1]). - Return the difference. No loop, no state change;
Pis read-only after the build.
F.4 State changes and the cost of an update
If one element changes, A[i] += δ, then every prefix that contains A[i] — that is P[i+1], …, P[n] — must also increase by δ. That is n − i writes, O(n) in the worst case. This is precisely the weakness that motivates Fenwick trees and segment trees. [2][7]
F.5 Pattern: prefix sums + hash map
Many problems ask not for one range but for how many (or the longest/shortest) subarrays satisfy a sum condition. A subarray A[i..j−1] has sum P[j] − P[i], so “sum equals k” becomes “P[i] = P[j] − k for some earlier i”. Scanning left to right, we keep a dictionary seen counting how often each prefix value has occurred; at each new position we look up running − k. This reduces the Θ(n2) pairs to one pass with expected O(1) dictionary operations. [14][16]
- For
nums = [1, 2, 3, −2, 2, 1], the prefix values are0, 1, 3, 6, 4, 6, 7. - Every purple arc joins two prefix positions whose values differ by
k = 3; each arc is one valid subarray. - There are 5 arcs, so the answer is 5. By prefix positions: (0,2) →
[1,2]; (2,3) →[3]; (2,5) →[3,−2,2]; (1,4) →[2,3,−2]; (4,6) →[2,1].
F.6 Extension: two dimensions
For a grid G with r rows and c columns, define a padded table S of size (r+1) × (c+1) where S[i][j] is the sum of the rectangle from (0,0) to (i−1, j−1). It is built row by row with
where the last term removes the corner counted twice. Any rectangle with corners (r1, c1) and (r2, c2) is then answered from four table entries:
Building takes O(rc) and each query O(1). [4] In graphics and vision the same table is the summed-area table or integral image: any rectangle sum needs exactly four references, regardless of its size. [9][11]
- Start from the green region: everything above-left of the target’s bottom-right corner.
- Subtract the two red regions (rows above the target; columns left of it).
- The purple top-left block was subtracted twice, so add it back once.
S[3][4] − S[1][4] − S[3][1] + S[1][1] = 28 − 8 − 9 + 3 = 14, which matches adding the six cells directly (6+3+2+2+0+1). Drag the same rectangle in Lab 3 to confirm.
F.7 Extension: the difference array (the inverse operation)
Prefix sums make range queries cheap. Their inverse makes range updates cheap. Define D[0] = A[0] and D[i] = A[i] − A[i−1]; then the prefix sums of D give back A. [14] To add v to every element of A[l..r], change only two entries: D[l] += v and D[r+1] −= v. After all updates, one prefix-sum pass reconstructs the array. Each update is O(1); the final rebuild is O(n). [4]
- Start with six zeros. Updates:
(1,3,+2),(2,5,+3),(0,1,−1). - Each update writes a green
+vat its start and a red−vjust after its end (slot 6 is a spare slot). - The final diff is
[−1, 2, 4, 0, −2, 0, −3]; its running sum over the first six slots is[−1, 1, 5, 5, 3, 3].
F.8 Edge cases
| Situation | What happens with the padded design |
|---|---|
| Empty array (n = 0) | P = [0]; no valid query exists, so the validator must reject every (L, R). |
| Range starting at 0 | P[R+1] − P[0] = P[R+1]; the sentinel removes the special case an unpadded array would need. [3] |
Single element L = R | P[L+1] − P[L] = A[L]. |
| Negative numbers | Work unchanged; P is no longer monotonic, so do not binary-search it. |
L > R or out of bounds | Python negative indices would silently wrap around and return garbage, so validate explicitly. |
| Floating-point values | Large prefixes can absorb small values; differences then suffer cancellation (see Section L). [18] |
GMathematical foundation
G.1 Definitions
The range sum is S(L, R) = Σk=LR A[k]. Using half-open intervals [i, j), as CMU’s notes do, the formula is the especially clean S[i, j) = P[j] − P[i]. [2]
G.2 The loop invariant and its proof
Initialisation. Before iteration 0, only P[0] = 0 is claimed, and the empty sum is 0. ✔
Maintenance. If P[i] = Σk<i A[k], the loop sets P[i+1] = P[i] + A[i] = Σk<i+1 A[k]. ✔
Termination. After iteration n−1, all of P[0..n] are correct. ∎
G.3 Why the query formula is correct (telescoping)
The first L terms appear in both sums and cancel. Equivalently, Σk=LR (P[k+1] − P[k]) is a telescoping sum in which every interior term cancels. This uses two algebraic facts about +: it is associative (so grouping does not matter) and it has an inverse (subtraction). [1]
G.4 2D: inclusion–exclusion
Let S(i, j) be the sum of the top-left i × j block. Splitting the block at row i−1 and column j−1 and applying inclusion–exclusion gives the build recurrence S(i, j) = G[i−1][j−1] + S(i−1, j) + S(i, j−1) − S(i−1, j−1); applying it to the query gives the four-term formula in F.6. [4] In d dimensions the same principle uses 2d corner terms with alternating signs. [9]
G.5 Prefix sums and differences are inverses
Define the operators 𝒫 (prefix sum) and 𝒟 (adjacent difference). Then 𝒟(𝒫(A)) = A and 𝒫(𝒟(A)) = A: they are the discrete counterparts of integration and differentiation. [14] A range update “add v on [l, r]” changes the derivative only at the two boundaries — which is exactly why the difference array touches two cells.
G.6 The counting identity behind subarray problems
An array of length n has n(n+1)/2 non-empty contiguous subarrays, one for each pair 0 ≤ i < j ≤ n of prefix positions. A condition on a subarray sum is therefore a condition on a pair of prefix values. “Sum = k” becomes “P[i] = P[j] − k”; “sum divisible by m” becomes “P[i] ≡ P[j] (mod m)”; “maximum sum” becomes “P[j] − mini<j P[i]”. Each converts a quadratic search over pairs into one linear scan with a dictionary or a running minimum. [4][13]
HOperations and complexity analysis
Assumptions: n = array length, q = number of queries, u = number of updates, arithmetic on numbers is O(1) (true for fixed-width machine integers; Python’s big integers cost time proportional to their digit length, which is negligible for normal values). Dictionary costs are expected-case for hashing. [16]
| Operation | Best case | Average case | Worst case | Auxiliary space |
|---|---|---|---|---|
| Build 1D prefix array | Θ(n) | Θ(n) | Θ(n) | Θ(n) (or O(1) if done in place) |
| Range-sum query | Θ(1) | Θ(1) | Θ(1) | O(1) |
Point update A[i] += δ (keep P valid) | Θ(1) (i = n−1) | Θ(n) | Θ(n) (i = 0) | O(1) |
| Naive range sum (no preprocessing) | Θ(1) (L = R) | Θ(n) | Θ(n) | O(1) |
| q queries, prefix method (total) | Θ(n + q) | Θ(n + q) | Θ(n + q) | Θ(n) |
| Build 2D table (r × c) | Θ(rc) | Θ(rc) | Θ(rc) | Θ(rc) |
| 2D rectangle query | Θ(1) | Θ(1) | Θ(1) | O(1) |
| Difference-array range update | Θ(1) | Θ(1) | Θ(1) | Θ(n) for D |
| Difference-array rebuild | Θ(n) | Θ(n) | Θ(n) | Θ(n) |
| Subarray-sum-equals-k (prefix + dict) | Θ(n) | Θ(n) expected | O(n²) under pathological hash collisions | O(n) |
Reasoning behind each entry
Build. The loop runs exactly n times doing constant work, independent of the values, so best, average and worst cases coincide: Θ(n) (both O(n) and Ω(n)). [3] No algorithm can do better, because every element must be read at least once to know the total — a lower bound of Ω(n).
Query. Two reads and one subtraction regardless of L, R: Θ(1). [2]
Update. Changing A[i] invalidates P[i+1..n]: n − i writes. Averaged over uniformly random i that is about n/2, still Θ(n). With roughly equal numbers of updates and queries, the average cost per operation is Θ(n) — CMU’s notes describe this as the point where plain prefix sums stop being adequate. [2]
Hash-map pattern. One pass of n iterations, each doing one lookup and one insert. Python’s dict has O(1) average and O(n) amortised-worst-case cost per operation, so the theoretical worst case is O(n2); in practice, with integer keys and Python’s hashing, the expected Θ(n) is what you observe. [16]
Amortised view and time–space trade-off
If you answer q queries, the one-time Θ(n) build is spread across them: amortised cost per query is Θ(n/q + 1). Prefix sums pay off as soon as you expect more than a handful of queries over long ranges. The trade is n+1 extra numbers of memory; for the 2D case it is a full extra table the size of the grid. Summed-area tables also need more bits per entry than the original data, because the totals grow — Crow’s paper discusses this storage cost for textures. [10]
Theory versus actual Python behaviour
- Constant factors. A Python-level
forloop is interpreted;itertools.accumulateruns the same loop in C, and NumPy’scumsumruns it over a typed buffer. All three are Θ(n), but the built-ins are usually much faster in wall-clock time. [5][6] - Hidden linear costs.
sum(A[L:R+1])is O(R−L) for the slice and O(R−L) for the sum — never constant. [16] - Integer size. Python ints never overflow; NumPy integer arithmetic is modular and raises no error on overflow. [17][6]
IPython implementation
I.1 Implementation from scratch
class PrefixSum:
"""Static range-sum structure. Build O(n), query O(1)."""
def __init__(self, arr):
self.n = len(arr)
self.P = [0] * (self.n + 1) # P[0] = 0 is the sentinel
for i, x in enumerate(arr):
self.P[i + 1] = self.P[i] + x # invariant: P[i+1] = A[0] + ... + A[i]
def range_sum(self, left, right):
"""Sum of A[left..right], both inclusive (0-indexed)."""
if not (0 <= left <= right < self.n):
raise IndexError(f"invalid range [{left}, {right}] for n={self.n}")
return self.P[right + 1] - self.P[left]
if __name__ == "__main__":
A = [3, 1, 4, 1, 5, 9, 2, 6]
ps = PrefixSum(A)
print("P =", ps.P)
print("sum(2..5) =", ps.range_sum(2, 5))
print("sum(0..7) =", ps.range_sum(0, 7))
print("sum(4..4) =", ps.range_sum(4, 4))
try:
ps.range_sum(5, 2)
except IndexError as e:
print("IndexError:", e)
print("empty P =", PrefixSum([]).P)
Line-by-line explanation
| Line | Why it is there |
|---|---|
| self.P = [0] * (self.n + 1) | Allocates n+1 slots in one step; slot 0 already holds the sentinel 0, the sum of the empty prefix. |
| for i, x in enumerate(arr) | One left-to-right pass; enumerate gives index and value together. |
| self.P[i + 1] = self.P[i] + x | The recurrence. Writing to i + 1 (not i) is the off-by-one shift that makes P[k] mean “first k elements”. |
| if not (0 <= left <= right < self.n) | Rejects reversed and out-of-range queries. Without it, a negative index would silently read from the end of the list. |
| return self.P[right + 1] - self.P[left] | The telescoping formula from G.3. |
Sample output (verified by running the code)
P = [0, 3, 4, 8, 9, 14, 23, 25, 31]
sum(2..5) = 19
sum(0..7) = 31
sum(4..4) = 5
IndexError: invalid range [5, 2] for n=8
empty P = [0]
Dry-run table — building P for A = [3, 1, 4, 1, 5, 9, 2, 6]
| i | A[i] | P[i] (before) | P[i+1] = P[i] + A[i] | P after step |
|---|---|---|---|---|
| — | — | — | init | [0, 0, 0, 0, 0, 0, 0, 0, 0] |
| 0 | 3 | 0 | 3 | [0, 3, …] |
| 1 | 1 | 3 | 4 | [0, 3, 4, …] |
| 2 | 4 | 4 | 8 | [0, 3, 4, 8, …] |
| 3 | 1 | 8 | 9 | [0, 3, 4, 8, 9, …] |
| 4 | 5 | 9 | 14 | […, 9, 14, …] |
| 5 | 9 | 14 | 23 | […, 14, 23, …] |
| 6 | 2 | 23 | 25 | […, 23, 25, …] |
| 7 | 6 | 25 | 31 | [0, 3, 4, 8, 9, 14, 23, 25, 31] |
I.2 Built-in Python alternatives
from itertools import accumulate
import numpy as np
A = [3, 1, 4, 1, 5, 9, 2, 6]
# 1) itertools.accumulate (Python 3.8+ for initial=)
P = list(accumulate(A, initial=0)) # [0, 3, 4, 8, 9, 14, 23, 25, 31]
# 2) NumPy: inclusive cumulative sum; prepend 0 for the padded form
P_np = np.concatenate(([0], np.cumsum(A)))
# 3) Other operators come for free with accumulate
import operator
running_max = list(accumulate(A, max)) # [3, 3, 4, 4, 5, 9, 9, 9]
running_prod = list(accumulate(A, operator.mul)) # prefix products
accumulate returns running totals by default, accepts any two-argument function, and with initial= emits one more element than the input — exactly the padded P. The function argument was added in Python 3.3 and initial in 3.8. [5] numpy.cumsum returns the inclusive cumulative sum along an axis; its accumulator type defaults to the input dtype (promoted to the platform integer for small integer types), and integer arithmetic is modular with no error on overflow. [6]
I.3 Prefix sum + hash map: subarray sum equals k
from collections import defaultdict
def subarray_sum_equals_k(nums, k):
count = 0
running = 0
seen = defaultdict(int)
seen[0] = 1 # the empty prefix: lets subarrays start at index 0
for x in nums:
running += x
count += seen[running - k] # earlier prefixes equal to running-k end a valid subarray here
seen[running] += 1 # record AFTER the lookup (prevents empty subarrays when k == 0)
return count
print(subarray_sum_equals_k([1, 2, 3, -2, 2, 1], 3)) # 5
Dry-run table — nums = [1, 2, 3, −2, 2, 1], k = 3 (verified)
| i | x | running | look up running − k | matches added | count | seen after step |
|---|---|---|---|---|---|---|
| 0 | 1 | 1 | −2 | 0 | 0 | {0:1, 1:1} |
| 1 | 2 | 3 | 0 | 1 | 1 | {0:1, 1:1, 3:1} |
| 2 | 3 | 6 | 3 | 1 | 2 | {…, 6:1} |
| 3 | −2 | 4 | 1 | 1 | 3 | {…, 4:1} |
| 4 | 2 | 6 | 3 | 1 | 4 | {…, 6:2} |
| 5 | 1 | 7 | 4 | 1 | 5 | {0:1, 1:1, 3:1, 6:2, 4:1, 7:1} |
A brute-force check over all 21 subarrays also returns 5. Time Θ(n) expected, space O(n) for the dictionary.
I.4 2D prefix sums
class PrefixSum2D:
def __init__(self, grid):
rows = len(grid)
cols = len(grid[0]) if grid else 0
self.S = [[0] * (cols + 1) for _ in range(rows + 1)] # zero row + zero column
for r in range(rows):
for c in range(cols):
self.S[r + 1][c + 1] = (grid[r][c] + self.S[r][c + 1]
+ self.S[r + 1][c] - self.S[r][c])
def region_sum(self, r1, c1, r2, c2):
"""Sum of grid[r1..r2][c1..c2], all bounds inclusive."""
S = self.S
return S[r2 + 1][c2 + 1] - S[r1][c2 + 1] - S[r2 + 1][c1] + S[r1][c1]
G = [[3, 0, 1, 4, 2],
[5, 6, 3, 2, 1],
[1, 2, 0, 1, 5],
[4, 1, 0, 1, 7]]
print(PrefixSum2D(G).region_sum(1, 1, 2, 3)) # 14
Note [[0] * (cols + 1) for _ in range(rows + 1)]: writing [[0] * (cols + 1)] * (rows + 1) instead would create one row object referenced many times — a classic Python aliasing bug. Build Θ(rc), query Θ(1). [4]
I.5 Difference array
def apply_range_updates(n, updates):
"""updates: list of (l, r, v) meaning add v to A[l..r] inclusive. Start from zeros."""
diff = [0] * (n + 1) # one spare slot so r + 1 == n is safe
for l, r, v in updates:
if not (0 <= l <= r < n):
raise IndexError(f"bad update range [{l}, {r}]")
diff[l] += v
diff[r + 1] -= v
out, running = [], 0
for i in range(n): # prefix-sum the difference array
running += diff[i]
out.append(running)
return out
print(apply_range_updates(6, [(1, 3, 2), (2, 5, 3), (0, 1, -1)])) # [-1, 1, 5, 5, 3, 3]
Time Θ(u + n) for u updates; space Θ(n). [4][14]
I.6 Comparison of implementations
| Implementation | Time | Extra space | Strengths | Watch out for |
|---|---|---|---|---|
| Manual loop (class above) | Θ(n) | Θ(n) | Explicit, easy to extend (validation, custom operators) | Slowest constant factor in CPython |
accumulate(A, initial=0) | Θ(n) | Θ(n) once listed | Short, fast, lazy iterator, any binary function [5] | initial needs Python 3.8+ |
numpy.cumsum | Θ(n) | Θ(n) | Vectorised; supports axes for 2D (cumsum(axis=0) then axis=1) [6] | Silent integer overflow; inclusive form (prepend 0 yourself) |
| In-place overwrite of A | Θ(n) | O(1) | No extra memory | Destroys the original data; loses the sentinel |
JReal-world applications
Only applications with a direct, documented use of prefix sums are listed. Where a scenario is our own illustration rather than a cited system, it is marked as such.
J.1 Computer vision and graphics: integral images
Viola and Jones’ real-time face detector evaluates a large number of rectangle (Haar-like) features in every image window. They introduced the integral image — a 2D prefix sum computed in a few operations per pixel — so that each rectangle feature can be evaluated in constant time at any scale or location; they credit Crow’s 1984 summed-area tables as the graphics precursor. [11][10] Crow’s original use was texture filtering: averaging a texture over a rectangle at a cost independent of the rectangle’s size. [10]
- Precompute the integral image
IIonce per frame. - A rectangle’s pixel sum =
II(D) − II(B) − II(C) + II(A)using its four corner points. - A two-rectangle Haar feature (light region minus dark region) needs just two such sums.
J.2 Databases and analytics: running totals
SQL window functions compute prefix sums declaratively. PostgreSQL’s tutorial shows sum(salary) OVER (ORDER BY salary) producing a running total, because with ORDER BY the default frame runs from the start of the partition through the current row (plus peers with equal sort keys). [21] Backend reporting code (cumulative revenue, cumulative sign-ups, “month-to-date” dashboards) uses exactly this, and the subtraction trick turns two cumulative values into any period total.
J.3 Search engines: decoding gap-encoded postings lists
Inverted indexes store each term’s sorted list of document IDs. Because consecutive IDs are close together, indexes store the gaps between them (for example 107, 5, 43 instead of 283154, 283159, 283202), which need far fewer bits. [22] Recovering the actual IDs is a prefix sum over the gaps — the gap list is a difference array, and decoding is its inverse.
J.4 Sorting and systems: computing output positions
Counting sort counts how many items have each key and then takes cumulative sums of the counts; the cumulative sum for a key tells you where that key’s block begins in the output. MIT 6.006 implements counting sort this way, and radix sort uses it as a stable subroutine. [15][8] The same “prefix sum of sizes gives offsets” idea appears whenever variable-sized records are packed contiguously into a buffer.
J.5 Parallel and distributed computing: scan as a primitive
Blelloch showed that many parallel algorithms — split radix sort, quicksort, line drawing, minimum spanning tree — can be built from scan operations, and the Connection Machine supported scans directly. [1] On GPUs, parallel scan underlies stream compaction, radix sort and summed-area tables. [12] In distributed-memory programs, MPI provides MPI_Scan and MPI_Exscan so that each process can learn the total of the values held by the processes before it — e.g. to compute its write offset into a shared output file. [8]
J.6 Compression and data structures for dynamic data
When counts change over time (for example cumulative frequency tables whose counts keep changing), the static array is replaced by a Fenwick tree, which keeps prefix sums queryable and updatable in O(log n); Fenwick introduced it for cumulative frequency tables. [8][7] Pibiri and Venturini’s study of the prefix-sum problem benchmarks such structures because they sit inside many larger systems. [23]
KComparison with alternatives
| Approach | Preprocess | Range query | Point update | Range update | Space | Choose when… |
|---|---|---|---|---|---|---|
| Naive loop | — | O(n) | O(1) | O(n) | O(1) | Very few queries, or short ranges |
| Prefix sum array | O(n) | O(1) | O(n) | O(n) | O(n) | Static data, many sum queries [2] |
| Difference array | O(n) | O(n) (rebuild first) | O(1) | O(1) | O(n) | Many range updates, read the result at the end [4] |
| Fenwick tree (BIT) | O(n) | O(log n) | O(log n) | O(log n)* | O(n) | Interleaved updates and prefix/range sums; invertible ops [7] |
| Segment tree | O(n) | O(log n) | O(log n) | O(log n) with lazy propagation | O(n) | Updates plus non-invertible ops (min/max), complex queries [2] |
| All-pairs table | O(n²) | O(1) | O(n²) | O(n²) | O(n²) | Almost never; only tiny n |
*Range update with point query uses a BIT over the difference array; range update with range query uses two BITs. [7]
Related techniques that are often confused with prefix sums
| Technique | Relationship to prefix sums | Key restriction |
|---|---|---|
| Sliding window | Maintains one window sum incrementally while two pointers move. | Needs a monotonic condition (typically non-negative values) to know which pointer to move. Prefix + hash map handles negatives. |
| Kadane’s algorithm | Max subarray sum; equivalent to tracking P[j] − min P[i]. [4] | Answers one optimisation question, not arbitrary ranges. |
| Sparse table | Precomputes answers on power-of-two ranges for O(1) range min/max. | Static data; O(n log n) space. |
- Does the data change between queries? If not and the operator is invertible (sum, XOR), use prefix sums.
- If only range updates happen and you read the result once at the end, use a difference array.
- If updates and queries interleave: Fenwick tree for invertible operators, segment tree otherwise.
When to avoid prefix sums
- The array is updated frequently between queries (rebuild or fix-up costs O(n)). [2]
- The query operator has no inverse (min, max, gcd) — subtraction of prefixes is meaningless.
- Only one or two queries will ever be asked: the build costs as much as the naive answer.
- Floating-point data with huge dynamic range, where cancellation can destroy small range sums (Section L).
LCommon mistakes and misconceptions
L.1 Off-by-one: mixing inclusive and exclusive conventions
# P is the padded array (len n+1)
def range_sum(P, L, R):
return P[R] - P[L] # misses A[R]!# P[k] = sum of first k elements
def range_sum(P, L, R):
return P[R + 1] - P[L] # inclusive L..RPick one convention and write it as a comment beside the array. With the padded array, “inclusive [L, R]” is P[R+1] − P[L] and “half-open [i, j)” is P[j] − P[i]. [2]
L.2 Unpadded arrays and the L = 0 special case
pre = list(accumulate(A)) # inclusive, no sentinel
def range_sum(L, R):
return pre[R] - pre[L - 1] # L = 0 reads pre[-1]: the LAST element!P = list(accumulate(A, initial=0))
def range_sum(L, R):
return P[R + 1] - P[L] # L = 0 just reads P[0] = 0Python’s negative indexing turns this bug into a wrong number instead of a crash, which makes it especially dangerous.
L.3 Counting the empty prefix (forgetting seen[0] = 1)
In the hash-map pattern, omitting the initial entry for prefix value 0 misses every valid subarray that starts at index 0. For nums = [3], k = 3 the buggy version returns 0 instead of 1. Similarly, inserting running into the dictionary before looking up running − k counts the empty subarray when k = 0.
L.4 Using a sliding window when values can be negative
Two-pointer windows assume that extending the window never decreases its sum. With negatives (e.g. [1, −1, 1], k = 1) that assumption fails and windows are missed. The prefix + hash map approach does not rely on monotonicity.
L.5 Complexity misconceptions
- “
sum(A[L:R+1])is O(1) because it’s one line.” It is O(R − L): list slicing copies k elements. [16] - “Prefix sums make range updates fast.” No — they make queries fast; updates become O(n). Difference arrays are the update-friendly dual. [2][4]
- “Rebuilding P inside the query loop is fine.” That silently reintroduces O(nq).
- “The hash-map solution is O(n) worst case.” It is O(n) expected; dictionary operations have an O(n) worst case. [16]
L.6 Overflow and precision
Python ints never overflow, but NumPy and fixed-width languages do. The output below was produced by running the code:
import numpy as np
np.cumsum(np.array([2**62, 2**62], dtype=np.int64))
# array([ 4611686018427387904, -9223372036854775808]) <- wrapped silently
from itertools import accumulate
P = list(accumulate([1e16, 1.0, -1e16, 1.0], initial=0.0))
P[2] - P[1] # 0.0, but A[1] is 1.0 (absorbed: 1e16 + 1.0 == 1e16 in float64)
NumPy documents that integer arithmetic is modular and raises no error on overflow. [6] For floats, prefer integer units (cents, not dollars) or accurate summation such as math.fsum, which tracks multiple partial sums to avoid loss of precision. [18]
L.7 2D mistakes
- Forgetting to add back the overlap
+ S[r1][c1](double subtraction). - Creating rows with
[[0]*(c+1)]*(r+1)— all rows alias the same list. - Swapping row/column order in the formula when the grid is not square.
L.8 Interview mistakes
- Jumping to code without stating the convention (inclusive/exclusive, padded or not).
- Not asking whether values can be negative or zero — this decides sliding window vs prefix + hash map.
- Not mentioning the update cost when the interviewer adds “and the array can change”: the expected answer is “then I would switch to a Fenwick or segment tree.”
MInterview preparation
M.1 Recognising the pattern
| If the problem says… | Think… |
|---|---|
| “sum of elements between i and j”, many queries, no updates | Plain prefix array |
| “number of subarrays with sum k / divisible by k / equal 0s and 1s” | Prefix value + hash map of counts (or remainders) |
| “longest subarray with sum k” | Prefix + hash map storing the first index of each value |
| “add v to every element in [l, r]”, many times | Difference array |
| “sum of a sub-rectangle”, many queries | 2D prefix sums |
| “left total equals right total”, “product except self” | Prefix and suffix aggregates |
| “XOR of a range” | Prefix XOR |
M.2 Common interview questions (conceptual)
- Why do we pad the prefix array with a leading zero?
- Why can’t prefix sums answer range-minimum queries?
- What changes if the array is updated between queries?
- Why does the subarray-sum-equals-k solution start with
{0: 1}?
Answers are developed throughout Sections F–L; Section P has a self-test with a separate answer key.
M.3 Coding exercises
Easy
E1. Running Sum of 1d Array Easy — LeetCode 1480
Hint
This is the inclusive scan; you can do it in place.Optimised solution
def running_sum(nums):
for i in range(1, len(nums)):
nums[i] += nums[i - 1]
return nums
Θ(n) time, O(1) extra space.
E2. Range Sum Query – Immutable Easy — LeetCode 303 · also CSES 1646
Hint
Build the padded array in the constructor.Optimised solution
from itertools import accumulate
class NumArray:
def __init__(self, nums):
self.P = list(accumulate(nums, initial=0))
def sumRange(self, left, right):
return self.P[right + 1] - self.P[left]
Build Θ(n), query Θ(1), space Θ(n).
E3. Find Pivot Index Easy — LeetCode 724
Hint
Right sum = total − left − nums[i]. No array needed.Optimised solution
def pivot_index(nums):
total, left = sum(nums), 0
for i, x in enumerate(nums):
if left == total - left - x:
return i
left += x
return -1
# pivot_index([1, 7, 3, 6, 5, 6]) -> 3
Θ(n) time, O(1) space.
Medium
M1. Subarray Sum Equals K Medium — LeetCode 560
Hint
Values can be negative, so sliding window fails. Count earlier prefixes equal torunning − k.Optimised solution
See Section I.3 and Lab 2. Θ(n) expected time, O(n) space.
M2. Contiguous Array Medium — LeetCode 525
Hint
Map 0 → −1. Equal counts ⇔ subarray sum 0 ⇔ two equal prefix values. Store the first index of each prefix value.Optimised solution
def find_max_length(nums):
first = {0: -1} # prefix value 0 seen "before index 0"
best = running = 0
for i, x in enumerate(nums):
running += 1 if x == 1 else -1
if running in first:
best = max(best, i - first[running])
else:
first[running] = i
return best
Θ(n) expected time, O(n) space.
M3. Subarray Sums Divisible by K Medium — LeetCode 974
Hint
Two prefixes with the same remainder mod k bound a divisible subarray. Python’s% already returns a non-negative remainder for positive k.Optimised solution
def subarrays_div_by_k(nums, k):
cnt = [0] * k
cnt[0] = 1
running = ans = 0
for x in nums:
running = (running + x) % k
ans += cnt[running]
cnt[running] += 1
return ans
Θ(n + k) time, O(k) space. (In Java/C++ you must fix negative remainders manually.)
M4. Range Sum Query 2D – Immutable Medium — LeetCode 304 · CSES 1652 Forest Queries
Hint
PaddedS, inclusion–exclusion with four corners.Optimised solution
Section I.4’s PrefixSum2D. Build Θ(rc), query Θ(1).
M5. Corporate Flight Bookings Medium — LeetCode 1109 (similar: Car Pooling, 1094)
Hint
Each booking is a range update; flights are 1-indexed.Optimised solution
from itertools import accumulate
def corp_flight_bookings(bookings, n):
diff = [0] * (n + 1)
for first, last, seats in bookings: # 1-indexed, inclusive
diff[first - 1] += seats
diff[last] -= seats
return list(accumulate(diff[:n]))
Θ(b + n) time, Θ(n) space.
M6. Product of Array Except Self Medium — LeetCode 238
Hint
Division is banned (and breaks on zeros). Use an exclusive prefix product times an exclusive suffix product.Optimised solution
def product_except_self(nums):
n = len(nums)
out = [1] * n
pre = 1
for i in range(n): # out[i] = product of nums[:i]
out[i] = pre
pre *= nums[i]
suf = 1
for i in range(n - 1, -1, -1): # multiply by product of nums[i+1:]
out[i] *= suf
suf *= nums[i]
return out
Θ(n) time, O(1) extra space besides the output.
Hard
H1. Number of Submatrices That Sum to Target Hard — LeetCode 1074
Hint
Fix a pair of rows (top, bottom); collapse the strip into a 1D array of column sums; then it is exactly Subarray Sum Equals K.Optimised solution
from collections import defaultdict
def num_submatrix_sum_target(matrix, target):
R, C = len(matrix), len(matrix[0])
ans = 0
for top in range(R):
col = [0] * C
for bottom in range(top, R):
for c in range(C):
col[c] += matrix[bottom][c] # column sums of the strip
seen = defaultdict(int); seen[0] = 1
running = 0
for v in col: # 1D subarray-sum-equals-k
running += v
ans += seen[running - target]
seen[running] += 1
return ans
Θ(R²·C) expected time, O(C) space (transpose first if R > C).
H2. Shortest Subarray with Sum at Least K Hard — LeetCode 862
Hint
Negatives allowed. Over prefix values, keep a deque of indices with increasingP: pop from the front while P[j] − P[front] ≥ k (record length), pop from the back while P[back] ≥ P[j].Optimised solution
from collections import deque
from itertools import accumulate
def shortest_subarray(nums, k):
P = list(accumulate(nums, initial=0))
best = len(nums) + 1
dq = deque()
for j, pj in enumerate(P):
while dq and pj - P[dq[0]] >= k:
best = min(best, j - dq.popleft())
while dq and P[dq[-1]] >= pj:
dq.pop()
dq.append(j)
return best if best <= len(nums) else -1
Θ(n) time: each index enters and leaves the deque at most once. Space Θ(n).
NAdvanced concepts
This section shows how the simple running total grows into more powerful structures. Skim it on a first reading; return when you meet problems with updates or parallel hardware.
N.1 Prefix sums under updates: the Fenwick tree
The static array fails when values change, because one update touches O(n) prefixes. A Fenwick tree (binary indexed tree) stores, at index i, the sum of a block that ends at i and whose length is the lowest set bit of i. Any prefix is the sum of O(log n) such blocks, and any element lies in O(log n) blocks, so both prefix queries and point updates cost O(log n) with O(n) memory. [7][8]
tree[i]covers thelowbit(i) = i & −ipositions ending ati: tree[1] covers 1, tree[2] covers 1–2, tree[4] covers 1–4, tree[6] covers 5–6, tree[8] covers 1–8.prefix(7)= tree[7] + tree[6] + tree[4] (green): repeatedly strip the lowest set bit, 7 → 6 → 4 → 0.- An update at position 5 touches tree[5], tree[6], tree[8]: repeatedly add the lowest set bit, 5 → 6 → 8.
class Fenwick:
"""1-indexed binary indexed tree for prefix sums with point updates."""
def __init__(self, n):
self.n = n
self.tree = [0] * (n + 1)
def add(self, i, delta): # A[i] += delta, 1-indexed
while i <= self.n:
self.tree[i] += delta
i += i & -i # jump to the next block that contains i
def prefix(self, i): # A[1] + ... + A[i]
s = 0
while i > 0:
s += self.tree[i]
i -= i & -i # strip the lowest set bit
return s
def range_sum(self, l, r): # inclusive, 1-indexed
return self.prefix(r) - self.prefix(l - 1)
A segment tree generalises further: it supports updates with non-invertible operators such as min and max, and with lazy propagation it supports range updates with range queries. [2]
N.2 Parallel prefix sums (scan)
The sequential loop has a dependency chain, so it looks impossible to parallelise; Blelloch called the operation a good example of a computation that seems inherently sequential yet has an efficient parallel algorithm. [1][12] Two classic schemes:
- Hillis–Steele: in round d, every element adds the value 2d positions to its left. After ⌈log₂ n⌉ rounds the scan is done, but the total work is O(n log n) — not work-efficient. [12][8]
- Work-efficient (up-sweep / down-sweep): build a reduction tree bottom-up, then push partial sums down. It does O(n) work with about 2 log₂ n steps, and is the basis of the GPU implementation in GPU Gems 3. [1][12][20]
- Round 0 (offset 1): each element adds its left neighbour.
- Round 1 (offset 2) and round 2 (offset 4) double the reach each time.
- After 3 = log₂ 8 rounds every position holds the inclusive prefix:
[3, 4, 8, 9, 14, 23, 25, 31].
N.3 Other invertible operators
- Prefix XOR: X[R+1] ⊕ X[L] gives range XOR, since XOR is its own inverse.
- Prefix counts: one prefix array per category (e.g. 26 for letters) answers “how many of each letter in s[l..r]?” in O(1) per letter. [3]
- Modular prefix sums: remainders mod m, as in LeetCode 974.
- Higher-order integral images: storing prefix sums of x and of x² gives the variance of any rectangle in O(1). [9]
N.4 2D difference arrays and the “imos” method
Range updates on rectangles work like the 1D case with four marks: +v at (r1, c1), −v at (r1, c2+1) and (r2+1, c1), +v at (r2+1, c2+1); a 2D prefix pass then materialises the grid. USACO’s “Painting the Barn” is the standard practice problem. [4]
N.5 Prefix sums on trees and lists
The same idea applies to root-to-node paths: store the sum from the root to each node; the sum of a path between u and v is pre(u) + pre(v) − 2·pre(lca) + val(lca). Blelloch also discusses the linked-list version of all-prefix-sums (list ranking), which is the basis of many parallel tree algorithms. [1][8]
N.6 Engineering trade-offs at scale
Pibiri and Venturini benchmark many prefix-sum data structures and find that practical factors — branch-free versus branchy traversal, cache conflicts in the Fenwick tree layout, SIMD for updates and wide tree fan-outs — change which structure wins on modern CPUs; for example, a 64-ary segment tree was their best general-purpose choice for arbitrary 64-bit updates. [23]
ONotebook-ready summary
First, the whole idea on one page — copy this sheet into your notebook. The detailed revision notes follow it.
A pre-processing trick: build a second array that stores the running total — the sum of everything before each position. Then any range sum is one subtraction.
prefix[i+1] = prefix[i] + arr[i]
The leading 0 means “sum of nothing”. prefix has n + 1 slots.
Sum of arr[L..R] (both ends included) in O(1):
Everything up to R, minus everything before L.
first i elements
= arr[0] + arr[1] + … + arr[i−1]
Given array:
Build the prefix array (add as you go):
Sum from L = 1 to R = 3 → 4 + (−1) + 3
= 8 − 2 = 6
Spend a little extra space and O(n) once, then answer every range-sum question in O(1).
| Build prefix array | O(n) |
| Each range query | O(1) |
| Extra space | O(n) |
| Change one element | O(n) |
- Range sums in O(1) time.
- Simple and short to code.
- Works with positive, negative or mixed numbers.
- 📊Range sum queries (most common).
- 🔢Counting subarrays with sum = k (prefix + hash map).
- ▦2D prefix sums for any rectangle in a grid.
- ➕Difference array: many range updates.
- Off-by-one: it is
R+1, notR. - Array changes often? Use a Fenwick tree.
- Doesn’t work for min / max ranges.
Detailed revision notes
1 · Definition
- Prefix sum array
P(len n+1):P[0]=0,P[i+1]=P[i]+A[i]. P[k]= sum of the first k elements.
2 · Core formula
sum(A[L..R]) = P[R+1] − P[L](half-open:P[j] − P[i])- Why: shared prefix A[0..L−1] cancels (telescoping).
3 · Picture to draw
4 · Key properties
- Needs an associative op with an inverse (+, XOR). Not max/min.
- Static data only — an update costs O(n).
- Prefix ⇄ difference are inverses (∫ and d/dx).
5 · Complexity
| Op | Time | Space |
|---|---|---|
| Build | Θ(n) | Θ(n) |
| Query | Θ(1) | O(1) |
| Point update | O(n) | O(1) |
| 2D build / query | Θ(rc) / Θ(1) | Θ(rc) |
| Diff range update / rebuild | Θ(1) / Θ(n) | Θ(n) |
6 · Python syntax
P = list(accumulate(A, initial=0))np.cumsum(A)(inclusive, watch overflow)- Count sum=k:
seen={0:1};cnt += seen.get(run-k,0); thenseen[run]+=1
7 · 2D formula
- build:
S[i+1][j+1] = G[i][j] + S[i][j+1] + S[i+1][j] − S[i][j] - query:
S[r2+1][c2+1] − S[r1][c2+1] − S[r2+1][c1] + S[r1][c1]
8 · Applications
- Integral images (Viola–Jones), summed-area tables (Crow ’84)
- SQL running totals, counting sort offsets, gap-decoding postings, GPU scan, MPI_Scan
9 · Interview takeaways
- State the convention first. Pad with 0.
- Negatives? → prefix + hash map, not sliding window.
- Updates? → Fenwick / segment tree. Range adds? → difference array.
- Subarray condition = condition on a pair of prefixes.
PKnowledge assessment
Attempt everything before opening the answer key at the end of this section.
P.1 Conceptual questions
- Why does the padded prefix array have length n+1, and what bug does the extra slot prevent?
- For which of these operators can a prefix array answer arbitrary range queries by “subtracting” prefixes: addition, multiplication, XOR, maximum, gcd? Explain.
- An array of size 106 receives 105 point updates interleaved with 105 range-sum queries. Estimate the cost with a plain prefix array, and name a better structure with its costs.
- Why does the two-pointer sliding window fail for “count subarrays with sum k” when values can be negative, and why does prefix + hash map still work?
- In the 2D query formula, why is
S[r1][c1]added rather than subtracted?
P.2 Dry-run exercises
- Build the padded
PforA = [5, −2, 7, 0, 3]and computesum(A[1..3])with the formula. - Trace
subarray_sum_equals_k([3, 4, 7, 2, −3, 1, 4, 2], 7): giverunning, the looked-up key andcountafter each step. - Starting from 5 zeros, apply the updates
(0, 2, +4)and(1, 4, −1)with a difference array. Show the difference array and the final array.
P.3 Coding problems
- Range XOR. Given
arrand queries[l, r], return the XOR ofarr[l..r]for each query in O(n + q) total (cf. LeetCode 1310). - Longest subarray with sum k. Values may be negative. Return the maximum length (0 if none) in expected O(n).
- Best k×k square. Given an r × c grid of integers and k, return the maximum sum of any k × k sub-square in O(rc).
P.4 Practical engineering scenario
You run a metrics service that stores one integer per second (requests served) for each of 10,000 services, keeping one year of history. Dashboards issue thousands of “total between timestamp t1 and t2” queries per second. Data for the current hour is still arriving, and occasionally a late correction changes a value from the past hour. Design the storage/query scheme, and state the time and space costs and the integer type you would use.
P.5 Answer key
Conceptual answers
P[k]means “sum of the first k elements”, so k ranges over 0…n: n+1 values. The slotP[0] = 0represents the empty prefix and makes ranges that start at index 0 use the same formula (P[R+1] − P[0]). Without it you need a special case, and in Python the unguardedpre[L−1]withL = 0silently reads the last element.- Addition (inverse: subtraction) and XOR (self-inverse) work. Multiplication works only if no element is zero (otherwise division is undefined) and is numerically risky for floats. Maximum and gcd have no inverse — knowing max(A[0..R]) and max(A[0..L−1]) does not determine max(A[L..R]) — so use a sparse table or segment tree.
- Each update costs up to 106 writes: roughly 105 × 5·105 ≈ 5·1010 operations on average — far too slow. A Fenwick tree gives O(log n) ≈ 20 steps per operation: about 4·106 steps total, plus O(n) build.
- The window method decides to shrink or grow based on whether the current sum is above or below k, which is only valid when adding elements can never decrease the sum. With negatives, a window that is “too big” might become valid after extending it further. The hash-map method enumerates, for each end position, all start positions implicitly via the equation
P[i] = P[j] − k, with no monotonicity assumption. - The top-left block above and to the left of the rectangle is contained in both subtracted strips (
S[r1][c2+1]andS[r2+1][c1]), so it was removed twice. AddingS[r1][c1]once restores the correct count (inclusion–exclusion).
Dry-run answers (verified by running code)
P = [0, 5, 3, 10, 10, 13].sum(A[1..3]) = P[4] − P[1] = 10 − 5 = 5(check: −2 + 7 + 0 = 5).-
Answer: 4 — the subarrays
i x running lookup running−7 found count 0 3 3 −4 0 0 1 4 7 0 1 1 2 7 14 7 1 2 3 2 16 9 0 2 4 −3 13 6 0 2 5 1 14 7 1 3 6 4 18 11 0 3 7 2 20 13 1 4 [3,4],[7],[7,2,−3,1],[1,4,2]. - diff (length 6) =
[4, −1, 0, −4, 0, 1]; final array =[4, 3, 3, −1, −1].
Coding answers
from itertools import accumulate
from operator import xor
# 1. Range XOR
def xor_queries(arr, queries):
X = list(accumulate(arr, xor, initial=0))
return [X[r + 1] ^ X[l] for l, r in queries]
# 2. Longest subarray with sum k (negatives allowed)
def longest_subarray_sum_k(nums, k):
first = {0: -1} # store the FIRST index of each prefix value
running = best = 0
for i, x in enumerate(nums):
running += x
if running - k in first:
best = max(best, i - first[running - k])
if running not in first: # never overwrite: earliest index gives longest span
first[running] = i
return best
# 3. Best k x k square
def best_square(grid, k):
R, C = len(grid), len(grid[0])
S = [[0] * (C + 1) for _ in range(R + 1)]
for r in range(R):
for c in range(C):
S[r + 1][c + 1] = grid[r][c] + S[r][c + 1] + S[r + 1][c] - S[r][c]
best = None
for r in range(k, R + 1):
for c in range(k, C + 1):
s = S[r][c] - S[r - k][c] - S[r][c - k] + S[r - k][c - k]
best = s if best is None else max(best, s)
return best
Complexities: (1) Θ(n + q); (2) Θ(n) expected, O(n) space; (3) Θ(rc) time and space.
Engineering scenario — model answer
Split the data by mutability. Closed hours (immutable) are stored per service as a cumulative array: one int64 running total per second, so any query fully inside history is C[t2+1] − C[t1] in O(1). One year is about 3.15·107 seconds, i.e. ≈252 MB per service at 8 bytes each — so in practice you also keep a coarser cumulative array per minute or hour and only load per-second blocks when needed (two-level prefix sums: whole buckets from the coarse array, partial buckets from the fine one).
Mutable recent window. The current and previous hour (≤ 7,200 seconds) accept writes and late corrections, so keep them in a Fenwick tree: O(log 7200) ≈ 13 steps per update or query. When an hour can no longer change, freeze it: compute its cumulative array in O(3600) and append it, offset by the running total so far.
Query. Split [t1, t2] into the frozen part (two lookups) plus the live part (two Fenwick prefix queries). Integer type: 64-bit signed — a year of per-second counts can exceed 231, and NumPy-style fixed-width arithmetic would wrap silently. [6][7]
QReferences and further reading
- G. E. Blelloch, “Prefix Sums and Their Applications,” Technical Report CMU-CS-90-190, School of Computer Science, Carnegie Mellon University, 1990. Formal all-prefix-sums/scan definition, associative operators, parallel implementation, applications (Sections B, G, J, N).
- Carnegie Mellon University, 15-451/651 Algorithm Design and Analysis, “Range query data structures” lecture notes, Fall 2025. Range-query problem, prefix-sum preprocessing O(n), query O(1), O(n) update weakness, motivation for segment trees (Sections C, F, H, K).
- D. Yao, D. Miao, “Introduction to Prefix Sums,” USACO Guide (Competitive Programming Initiative). Padded 1-indexed definition, O(1) range-sum formula, O(n) construction (Sections A–C, F, H).
- USACO Guide, “More on Prefix Sums” (Silver). 2D prefix-sum recurrence and query, max subarray via prefix minimum, difference arrays (Sections F, G, I, K, N).
- Python Software Foundation, itertools.accumulate — Python 3 documentation. Built-in running totals, custom functions (3.3+),
initialparameter (3.8+) (Sections H, I). - NumPy Developers, numpy.cumsum — NumPy reference. Cumulative sum along an axis, accumulator dtype rules, modular integer overflow with no error (Sections F, H, I, L).
- CP-Algorithms, “Fenwick Tree”. Fenwick tree operations, O(log n) costs, invertibility requirement, range-update variants (Sections B, G, K, N).
- Wikipedia contributors, “Prefix sum” (secondary overview; consulted for history and terminology, cross-checked with [1], [12]). Inclusive/exclusive scans, library names, history (Ofman, Ladner–Fischer, Hillis–Steele, Fenwick), parallel algorithms, counting sort and MPI uses.
- Wikipedia contributors, “Summed-area table” (secondary; cross-checked with [10], [11]). Four-reference rectangle sums, higher-order integral images, history (Sections F, G, J, N).
- F. C. Crow, “Summed-area tables for texture mapping,” Proc. SIGGRAPH ’84, Computer Graphics 18(3), pp. 207–212, ACM, 1984. Origin of the 2D prefix sum in graphics; storage cost per entry (Sections B, H, J).
- P. Viola, M. J. Jones, “Robust Real-Time Face Detection,” International Journal of Computer Vision 57(2), 137–154, 2004 (course copy hosted by Princeton COS 429). Integral image, constant-time rectangle features, credit to Crow (Sections F, J).
- M. Harris, S. Sengupta, J. D. Owens, “Parallel Prefix Sum (Scan) with CUDA,” GPU Gems 3, ch. 39, NVIDIA / Addison-Wesley, 2007. Exclusive scan definition, naive vs work-efficient parallel scan, GPU applications (Sections B, F, J, N).
- J. Brody, CS35X Competitive Programming, Lecture 9: Prefix Sums, Swarthmore College, 2024. pre[0] = 0 convention; max subarray via prefix sums (Sections B, G).
- PEGWiki, “Prefix sum array and difference array”. Difference array definition, inverse relationship (discrete integration/differentiation), hash-map counting (Sections B, F, G, I).
- MIT OpenCourseWare, 6.006 Introduction to Algorithms (Spring 2020), Recitation 5: Linear Sorting. Counting sort computing final positions via cumulative sums; radix sort (Section J).
- Python Wiki, “TimeComplexity”. CPython list get-item O(1), slice O(k), dict average O(1) / amortised worst O(n) (Sections C, F, H, L).
- Python Software Foundation, Built-in Types — Numeric Types. Python integers have unlimited precision (Sections F, H).
- Python Software Foundation, math.fsum. Accurate floating-point summation (Sections F, L).
- CSES Problem Set, “Static Range Sum Queries” (task 1646). Canonical problem statement and constraints n, q ≤ 2·10⁵, values ≤ 10⁹ (Sections C, F, M).
- A. Appel, COS 326 “Parallel Prefix Scan” lecture, Princeton University, 2020. Two-pass (reduce tree, then down pass) parallel scan (Section N).
- PostgreSQL Global Development Group, “Window Functions” tutorial, PostgreSQL documentation. Running totals via
sum(...) OVER (ORDER BY ...)and default frame (Section J). - C. D. Manning, P. Raghavan, H. Schütze, Introduction to Information Retrieval, §5.3 “Postings file compression”, Cambridge University Press (Stanford online edition). Gap encoding of docIDs in inverted indexes (Section J).
- G. E. Pibiri, R. Venturini, “Practical Trade-Offs for the Prefix-Sum Problem,” Software: Practice and Experience, 2021. Empirical comparison of prefix-sum data structures (Sections J, N).
Practice problem sources
LeetCode problems 238, 303, 304, 525, 560, 724, 862, 974, 1074, 1094, 1109, 1310, 1480 and CSES tasks 1646, 1652 are linked at their point of use in Sections M and P. Problem statements are owned by their respective sites.