DSA Learning Studio · Chapter on Array Techniques

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.

Difficulty: Beginner → Intermediate (advanced section: Upper-intermediate) Reading time: ~75 minutes (+ 30 min exercises) Language: Python 3.8+

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:

  1. Define a prefix sum array formally and informally, and explain the role of the leading zero (the sentinel).
  2. Answer any contiguous range-sum query in constant time using P[R+1] − P[L], and prove why it is correct.
  3. Analyse the build, query and update costs, and explain exactly when prefix sums stop being the right tool.
  4. Combine prefix sums with a hash map to count or find subarrays with a given property in linear time.
  5. Extend the idea to two dimensions (summed-area tables / integral images) using inclusion–exclusion.
  6. Use the inverse operation — the difference array — to apply many range updates in O(1) each.
  7. Recognise prefix-sum patterns in interview problems, and know the next structures to reach for (Fenwick tree, segment tree, parallel scan).
The one-sentence promise Spend O(n) time once to record running totals, and every later question of the form “what is the sum between positions L and R?” becomes a single subtraction. [2][3]
How the visuals in this chapter are made This environment has no image-generation model, so every “whiteboard” illustration is drawn in code: a small sketch renderer produces hand-drawn-style strokes and handwriting labels as SVG from the actual data in each example. That keeps every index, value and arrow exactly correct while still looking like marker on a whiteboard. All interactive labs below are fully working.

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]

Formal definition Given a sequence A = [a0, a1, …, an−1] and a binary associative operator ⊕, the all-prefix-sums operation returns [a0, (a0 ⊕ a1), …, (a0 ⊕ a1 ⊕ … ⊕ an−1)]. With ⊕ = +, the input [3 1 7 0 4 1 6 3] yields [3 4 11 11 15 16 22 25]. This is Blelloch’s definition from his 1990 Carnegie Mellon report, where the operation is also called a scan. [1][12]
Simple English definition A prefix sum array answers the question “how much has been added up so far?” for every position. Once you know the “so far” totals, the amount added between two positions is just the later total minus the earlier one.

In algorithm design we almost always use the exclusive, sentinel-padded form, which has one extra slot at the front:

P[0] = 0,    P[i+1] = P[i] + A[i]   for   0 ≤ i < n   ⟹   P[i] = A[0] + A[1] + … + A[i−1]

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:

  1. Precomputation trades space for time. Store n+1 extra numbers and queries drop from linear to constant time. [2]
  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]
  3. 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

ComponentSpecification
InputAn array A of n numbers that does not change, and q queries, each a pair (L, R) with 0 ≤ L ≤ R < n.
OutputFor each query, the value A[L] + A[L+1] + … + A[R].
Typical constraintsCompetitive-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 assumptionNo 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]

Real-world analogy: the odometer A car’s odometer shows the total kilometres driven since the car was built — a prefix sum of every trip. To know how far you drove between Monday morning and Friday evening you do not replay the week’s trips; you subtract Monday’s odometer reading from Friday’s. Recording the reading costs nothing extra while driving (the O(n) build), and every “how far between these two moments?” question becomes one subtraction (the O(1) query). (Illustrative analogy.)

DVisual whiteboard explanations

All diagrams in this chapter use one colour language. Learn it once and every picture reads the same way:

Blue — original data / the input array Green — results, prefix sums, selected answers Red — subtracted parts, deletions, errors Yellow/orange — active index, current pointer Purple — relationships, carries, connections Black — labels and definitions
Figure D.1 · Concept introductionFrom an array to its running totals
A[i] inputP[i] prefix sumcarry P[i] → P[i+1]element being added
  1. Start the green row with the sentinel P[0] = 0 — the sum of zero elements.
  2. For each i, carry the previous total (purple arrow) and add the blue value directly above-left (A[i]).
  3. The highlighted step shows P[6] = P[5] + A[5] = 14 + 9 = 23.
Technical interpretation: 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).
Figure D.2 · Memory & index representationWhat each P[k] “covers”
A in contiguous memorystored value of P[k]brace = elements summarisedindex labels
  1. Both arrays are ordinary contiguous lists; A has indices 0…7 and P has indices 0…8.
  2. A brace under A shows which elements a single green number summarises: P[3] covers A[0..2], P[6] covers A[0..5], P[8] covers everything.
  3. P[0] covers nothing — the empty prefix — which is why it is 0.
Technical interpretation: one stored integer replaces a whole loop. Because P is a contiguous array, P[k] is read in O(1) by address arithmetic, exactly like any list access.
Figure D.3 · Internal working of a querysum(L..R) = P[R+1] − P[L]
P[R+1]: prefix up to RP[L]: prefix before L (subtracted)the answer range L..R
  1. Query L = 2, R = 5 asks for 4 + 1 + 5 + 9.
  2. The long green brace P[6] = 23 covers A[0..5]; the short red brace P[2] = 4 covers A[0..1].
  3. Their overlap A[0..1] cancels, leaving exactly the yellow range: 23 − 4 = 19.
Technical interpretation: two O(1) array reads and one subtraction, independent of the range length R − L + 1. [2]
Figure D.4 · Before-and-after comparisonLooping per query vs two lookups
pointer visiting a cellrepeated workstored totals reused
  1. 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.
  2. After: the prefix method touches exactly two green cells per query, no matter how wide the range is.
Technical interpretation: naive cost Θ(R−L+1) per query, O(nq) total; prefix cost Θ(1) per query, Θ(n+q) total. [2]

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.

Lab 1 · Build & queryPrefix-sum builder and range-sum calculator
A
P

Query:

Tip: you can also click a cell in row A to set L, and shift-click (or click again) to set R. Queries only use P once it is fully built.

Lab 2 · Prefix sums + hash mapCount subarrays whose sum equals k
nums
seen (prefix sum → how many times seen):
Subarrays found:
Lab 3 · 2D prefix sumsDrag to select a rectangle
Drag across the left grid (or click two corners). The right table is S, padded with a zero row and column.
grid (blue)
S table (green) — corners used by the query
Lab 4 · Difference arrayMany range updates, one final pass
diff
result

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

  1. Allocate P of length n+1 filled with zeros. P[0] = 0 is now set.
  2. For i = 0, 1, …, n−1: read P[i] (the total so far), read A[i], write P[i+1] = P[i] + A[i].
  3. 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

  1. Validate 0 ≤ L ≤ R < n.
  2. Read P[R+1] (sum of A[0..R]) and P[L] (sum of A[0..L−1]).
  3. Return the difference. No loop, no state change; P is 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]

Figure F.1 · Step-by-step executionMatching prefix values that differ by k
numsrunning prefix valuepair (P[i], P[j]) with P[j] − P[i] = kmatched subarray
  1. For nums = [1, 2, 3, −2, 2, 1], the prefix values are 0, 1, 3, 6, 4, 6, 7.
  2. Every purple arc joins two prefix positions whose values differ by k = 3; each arc is one valid subarray.
  3. 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].
Technical interpretation: the hash map remembers how many earlier prefixes have each value, so repeated values (like 6 here) are counted correctly. Negative numbers are fine — unlike the sliding-window technique, nothing assumes monotonic sums.

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

S[i+1][j+1] = G[i][j] + S[i][j+1] + S[i+1][j] − S[i][j]

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:

sum = S[r2+1][c2+1] − S[r1][c2+1] − S[r2+1][c1] + S[r1][c1]

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]

Figure F.2 · Inclusion–exclusionFour corners answer any rectangle
target rectangle+ big corner S[r2+1][c2+1]− strips above and left+ overlap added back
  1. Start from the green region: everything above-left of the target’s bottom-right corner.
  2. Subtract the two red regions (rows above the target; columns left of it).
  3. The purple top-left block was subtracted twice, so add it back once.
Technical interpretation: on the example grid, rows 1–2 × columns 1–3 give 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]

Figure F.3 · Before and afterThree updates, two marks each
+v at l (range starts)−v at r+1 (range ends)diff arrayreconstructed array
  1. Start with six zeros. Updates: (1,3,+2), (2,5,+3), (0,1,−1).
  2. Each update writes a green +v at its start and a red −v just after its end (slot 6 is a spare slot).
  3. 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].
Technical interpretation: a range update becomes a “switch on at l, switch off after r” event; the prefix pass integrates the events. Cost O(u + n) for u updates, versus O(u·n) naively.

F.8 Edge cases

SituationWhat 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 0P[R+1] − P[0] = P[R+1]; the sentinel removes the special case an unpadded array would need. [3]
Single element L = RP[L+1] − P[L] = A[L].
Negative numbersWork unchanged; P is no longer monotonic, so do not binary-search it.
L > R or out of boundsPython negative indices would silently wrap around and return garbage, so validate explicitly.
Floating-point valuesLarge prefixes can absorb small values; differences then suffer cancellation (see Section L). [18]

GMathematical foundation

G.1 Definitions

P[i] = Σk=0i−1 A[k]   (0 ≤ i ≤ n),     with P[0] = 0 (empty sum)

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

InvariantAt the start of iteration i of the build loop, P[0..i] are correct: P[t] = Σk<t A[k] for all t ≤ i.

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)

P[R+1] − P[L] = Σk=0R A[k] − Σk=0L−1 A[k] = Σk=LR A[k]

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]

The inverse requirement mattersAny associative operator has a prefix scan (prefix max, prefix product, prefix XOR, …). [1][8] But only operators with an inverse let you subtract one prefix from another. XOR is its own inverse, so prefix XOR answers range XOR as X[R+1] ⊕ X[L]. Max has no inverse, so prefix max cannot answer an arbitrary range max — that needs a sparse table or segment tree. Products work only if no element is zero (division by zero). CP-Algorithms notes that a Fenwick tree likewise needs an invertible operation for general range queries. [7]

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]

OperationBest caseAverage caseWorst caseAuxiliary 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) expectedO(n²) under pathological hash collisionsO(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]

Lab 5 · Time-complexity visualisationHow many additions does each method perform?

Model: queries have random L ≤ R, so the naive method adds about (n+2)/3 elements per query on average (expected length of a random interval); the prefix method adds n during the build plus 1 subtraction per query. The bars use a logarithmic scale.

Theory versus actual Python behaviour

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

LineWhy 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] + xThe 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]

iA[i]P[i] (before)P[i+1] = P[i] + A[i]P after step
———init[0, 0, 0, 0, 0, 0, 0, 0, 0]
0303[0, 3, …]
1134[0, 3, 4, …]
2448[0, 3, 4, 8, …]
3189[0, 3, 4, 8, 9, …]
45914[…, 9, 14, …]
591423[…, 14, 23, …]
622325[…, 23, 25, …]
762531[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)

ixrunninglook up running − kmatches addedcountseen after step
011−200{0:1, 1:1}
123011{0:1, 1:1, 3:1}
236312{…, 6:1}
3−24113{…, 4:1}
426314{…, 6:2}
517415{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

ImplementationTimeExtra spaceStrengthsWatch 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 listedShort, 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 memoryDestroys 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]

Figure J.1 · Real-world applicationIntegral image: a box filter of any size in four lookups
pixelsfeature rectangle+ corners− corners
  1. Precompute the integral image II once per frame.
  2. A rectangle’s pixel sum = II(D) − II(B) − II(C) + II(A) using its four corner points.
  3. A two-rectangle Haar feature (light region minus dark region) needs just two such sums.
Technical interpretation: the cost per feature no longer depends on the feature’s area, which is what made scanning many window sizes in real time feasible. [11]

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]

Engineering illustration (our example)A web API logs one integer per minute: requests served. Product managers ask ad-hoc questions like “how many requests between 09:15 and 11:40 yesterday?”. Store the day’s 1,440 per-minute counts plus a 1,441-entry cumulative array; each question becomes one subtraction instead of a scan, and the cumulative array is computed once when the day closes (the data are static afterwards).

KComparison with alternatives

ApproachPreprocessRange queryPoint updateRange updateSpaceChoose when…
Naive loop—O(n)O(1)O(n)O(1)Very few queries, or short ranges
Prefix sum arrayO(n)O(1)O(n)O(n)O(n)Static data, many sum queries [2]
Difference arrayO(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 treeO(n)O(log n)O(log n)O(log n) with lazy propagationO(n)Updates plus non-invertible ops (min/max), complex queries [2]
All-pairs tableO(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

TechniqueRelationship to prefix sumsKey restriction
Sliding windowMaintains 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 algorithmMax subarray sum; equivalent to tracking P[j] − min P[i]. [4]Answers one optimisation question, not arbitrary ranges.
Sparse tablePrecomputes answers on power-of-two ranges for O(1) range min/max.Static data; O(n log n) space.
Figure K.1 · Comparison with alternative approachesWhich range-query tool should I pick?
questionrecommended structuredecision path
  1. Does the data change between queries? If not and the operator is invertible (sum, XOR), use prefix sums.
  2. If only range updates happen and you read the result once at the end, use a difference array.
  3. If updates and queries interleave: Fenwick tree for invertible operators, segment tree otherwise.
Technical interpretation: the decision hinges on two properties — mutability of the data and invertibility of the operator.

When to avoid prefix sums

LCommon mistakes and misconceptions

L.1 Off-by-one: mixing inclusive and exclusive conventions

✗ Incorrect
# P is the padded array (len n+1)
def range_sum(P, L, R):
    return P[R] - P[L]      # misses A[R]!
✓ Correct
# P[k] = sum of first k elements
def range_sum(P, L, R):
    return P[R + 1] - P[L]  # inclusive L..R

Pick 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

✗ Incorrect
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!
✓ Correct
P = list(accumulate(A, initial=0))
def range_sum(L, R):
    return P[R + 1] - P[L]      # L = 0 just reads P[0] = 0

Python’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

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

L.8 Interview mistakes

MInterview preparation

M.1 Recognising the pattern

If the problem says…Think…
“sum of elements between i and j”, many queries, no updatesPlain 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 timesDifference array
“sum of a sub-rectangle”, many queries2D 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)

  1. Why do we pad the prefix array with a leading zero?
  2. Why can’t prefix sums answer range-minimum queries?
  3. What changes if the array is updated between queries?
  4. 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

HintThis 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

HintBuild 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

HintRight 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

HintValues can be negative, so sliding window fails. Count earlier prefixes equal to running − k.
Optimised solution

See Section I.3 and Lab 2. Θ(n) expected time, O(n) space.

M2. Contiguous Array Medium — LeetCode 525

HintMap 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

HintTwo 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

HintPadded S, 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)

HintEach 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

HintDivision 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

HintFix 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

HintNegatives allowed. Over prefix values, keep a deque of indices with increasing P: 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]

Figure N.1 · Internal structureFenwick blocks for n = 8 (1-indexed)
array positions 1..8block stored at tree[i] = range (i − lowbit(i), i]blocks summed for prefix(7)
  1. tree[i] covers the lowbit(i) = i & −i positions ending at i: tree[1] covers 1, tree[2] covers 1–2, tree[4] covers 1–4, tree[6] covers 5–6, tree[8] covers 1–8.
  2. prefix(7) = tree[7] + tree[6] + tree[4] (green): repeatedly strip the lowest set bit, 7 → 6 → 4 → 0.
  3. An update at position 5 touches tree[5], tree[6], tree[8]: repeatedly add the lowest set bit, 5 → 6 → 8.
Technical interpretation: both loops run at most ⌊log₂ n⌋ + 1 times, giving O(log n) operations. [7]
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:

Figure N.2 · Execution diagramHillis–Steele inclusive scan on 8 elements
inputadd from 2^d to the leftvalues updated this roundfinal inclusive scan
  1. Round 0 (offset 1): each element adds its left neighbour.
  2. Round 1 (offset 2) and round 2 (offset 4) double the reach each time.
  3. After 3 = log₂ 8 rounds every position holds the inclusive prefix: [3, 4, 8, 9, 14, 23, 25, 31].
Technical interpretation: all additions in a round are independent, so with n processors each round takes O(1) time; total span O(log n), total work O(n log n). [12]

N.3 Other invertible operators

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.

Prefix Sum
What is 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.

Formula
prefix[0] = 0
prefix[i+1] = prefix[i] + arr[i]

The leading 0 means “sum of nothing”. prefix has n + 1 slots.

Range Sum Query

Sum of arr[L..R] (both ends included) in O(1):

sum(L, R) = prefix[R+1] − prefix[L]

Everything up to R, minus everything before L.

Visual Intuition
prefix[i] = sum of the
first i elements

= arr[0] + arr[1] + … + arr[i−1]

Example

Given array:

arr

Build the prefix array (add as you go):

prefix
Query Example

Sum from L = 1 to R = 3 → 4 + (−1) + 3

arr
sum(1, 3) = prefix[4] − prefix[1]
           = 8 − 2 = 6
★ Key Takeaway

Spend a little extra space and O(n) once, then answer every range-sum question in O(1).

Complexity
Build prefix arrayO(n)
Each range queryO(1)
Extra spaceO(n)
Change one elementO(n)
Benefits
  • Range sums in O(1) time.
  • Simple and short to code.
  • Works with positive, negative or mixed numbers.
Use Cases
  • 📊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.
Watch out
  • Off-by-one: it is R+1, not R.
  • 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

OpTimeSpace
BuildΘ(n)Θ(n)
QueryΘ(1)O(1)
Point updateO(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); then seen[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

  1. Why does the padded prefix array have length n+1, and what bug does the extra slot prevent?
  2. For which of these operators can a prefix array answer arbitrary range queries by “subtracting” prefixes: addition, multiplication, XOR, maximum, gcd? Explain.
  3. 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.
  4. 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?
  5. In the 2D query formula, why is S[r1][c1] added rather than subtracted?

P.2 Dry-run exercises

  1. Build the padded P for A = [5, −2, 7, 0, 3] and compute sum(A[1..3]) with the formula.
  2. Trace subarray_sum_equals_k([3, 4, 7, 2, −3, 1, 4, 2], 7): give running, the looked-up key and count after each step.
  3. 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

  1. Range XOR. Given arr and queries [l, r], return the XOR of arr[l..r] for each query in O(n + q) total (cf. LeetCode 1310).
  2. Longest subarray with sum k. Values may be negative. Return the maximum length (0 if none) in expected O(n).
  3. 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
  1. P[k] means “sum of the first k elements”, so k ranges over 0…n: n+1 values. The slot P[0] = 0 represents 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 unguarded pre[L−1] with L = 0 silently reads the last element.
  2. 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.
  3. 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.
  4. 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.
  5. The top-left block above and to the left of the rectangle is contained in both subtracted strips (S[r1][c2+1] and S[r2+1][c1]), so it was removed twice. Adding S[r1][c1] once restores the correct count (inclusion–exclusion).
Dry-run answers (verified by running code)
  1. P = [0, 5, 3, 10, 10, 13]. sum(A[1..3]) = P[4] − P[1] = 10 − 5 = 5 (check: −2 + 7 + 0 = 5).
  2. ixrunninglookup running−7foundcount
    033−400
    147011
    2714712
    3216902
    4−313602
    5114713
    64181103
    72201314
    Answer: 4 — the subarrays [3,4], [7], [7,2,−3,1], [1,4,2].
  3. 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

  1. 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).
  2. 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).
  3. 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).
  4. 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).
  5. Python Software Foundation, itertools.accumulate — Python 3 documentation. Built-in running totals, custom functions (3.3+), initial parameter (3.8+) (Sections H, I).
  6. 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).
  7. CP-Algorithms, “Fenwick Tree”. Fenwick tree operations, O(log n) costs, invertibility requirement, range-update variants (Sections B, G, K, N).
  8. 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.
  9. 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).
  10. 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).
  11. 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).
  12. 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).
  13. J. Brody, CS35X Competitive Programming, Lecture 9: Prefix Sums, Swarthmore College, 2024. pre[0] = 0 convention; max subarray via prefix sums (Sections B, G).
  14. PEGWiki, “Prefix sum array and difference array”. Difference array definition, inverse relationship (discrete integration/differentiation), hash-map counting (Sections B, F, G, I).
  15. 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).
  16. 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).
  17. Python Software Foundation, Built-in Types — Numeric Types. Python integers have unlimited precision (Sections F, H).
  18. Python Software Foundation, math.fsum. Accurate floating-point summation (Sections F, L).
  19. CSES Problem Set, “Static Range Sum Queries” (task 1646). Canonical problem statement and constraints n, q ≤ 2·10⁵, values ≤ 10⁹ (Sections C, F, M).
  20. A. Appel, COS 326 “Parallel Prefix Scan” lecture, Princeton University, 2020. Two-pass (reduce tree, then down pass) parallel scan (Section N).
  21. PostgreSQL Global Development Group, “Window Functions” tutorial, PostgreSQL documentation. Running totals via sum(...) OVER (ORDER BY ...) and default frame (Section J).
  22. 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).
  23. 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.