Simple Algorithm
Algorithms & Data Structures · Optimal · 24 min

2-D Prefix Sums & Inclusion–Exclusion

Summed-area tables, rectangle queries and higher dimensions.

Viola and Jones's face detector (2001) ran in real time by testing simple rectangle features at every position and scale of every frame. Each feature, whatever its size, cost a handful of memory lookups, thanks to a table that Frank Crow had introduced to computer graphics in 1984. The same four-corner formula, generalized to the nn-dimensional hypercube, sums a function over all subsets of every set in O(n 2n)O(n\,2^n).

What you’ll learn

  • Build a summed-area table in O(RC)O(RC) and prove the four-term rectangle formula by inclusion–exclusion.
  • Generalize to dd dimensions: 2d2^d signed corners per query, but only dd one-dimensional passes to build the table.
  • Treat sums over subsets as prefix sums on the hypercube {0,1}n\{0,1\}^n: compute the zeta transform in O(n 2n)O(n\,2^n) and invert it by Möbius inversion.
  • Explain what subtraction buys, and why dynamic prefix sums need Ω(log⁡n)\Omega(\log n) time per operation in the cell-probe model.

Summed-area tables

∑x=r1r2∑y=c1c2a[x][y]  =  S[r2+1][c2+1]−S[r1][c2+1]−S[r2+1][c1]+S[r1][c1]\sum_{x=r_1}^{r_2}\sum_{y=c_1}^{c_2}a[x][y]\;=\;S[r_2+1][c_2+1]-S[r_1][c_2+1]-S[r_2+1][c_1]+S[r_1][c_1]
Any rectangle with inclusive corners (r1,c1)(r_1,c_1) and (r2,c2)(r_2,c_2) costs four lookups. The table itself is built in O(RC)O(RC) by the same identity read backward: S[i+1][j+1]=a[i][j]+S[i][j+1]+S[i+1][j]−S[i][j]S[i+1][j+1]=a[i][j]+S[i][j+1]+S[i+1][j]-S[i][j].
DerivationProof by inclusion–exclusion
  1. [r1≤x≤r2]=[x≤r2]−[x≤r1−1],[c1≤y≤c2]=[y≤c2]−[y≤c1−1][r_1\le x\le r_2]=[x\le r_2]-[x\le r_1-1],\qquad [c_1\le y\le c_2]=[y\le c_2]-[y\le c_1-1]

    Write the rectangle's indicator as a product of two 1-D ranges, and each range as a difference of two prefixes:

  2. [x≤r2][y≤c2]−[x<r1][y≤c2]−[x≤r2][y<c1]+[x<r1][y<c1][x\le r_2][y\le c_2]-[x<r_1][y\le c_2]-[x\le r_2][y<c_1]+[x<r_1][y<c_1]

    Multiply out: four signed "top-left blocks", each of which is one entry of SS:

  3. rectangle=S[r2+1][c2+1]−S[r1][c2+1]−S[r2+1][c1]+S[r1][c1]\text{rectangle}=S[r_2+1][c_2+1]-S[r_1][c_2+1]-S[r_2+1][c_1]+S[r_1][c_1]

    Weight by a[x][y]a[x][y] and sum over the grid. The block [r1,r2]×[c1,c2][r_1,r_2]\times[c_1,c_2] is counted once; the strips above it and left of it are subtracted once each; the corner block above and to the left is subtracted twice and added back once. That is inclusion–exclusion.

Predict before you look

In the grid above (rows and columns numbered from 0), the table has S[3][4]=60S[3][4]=60, S[1][4]=9S[1][4]=9, S[3][1]=17S[3][1]=17 and S[1][1]=3S[1][1]=3. What is the sum of the rectangle with rows 1..21..2 and columns 1..31..3, inclusive?

Show the answer

37

S[3][4]−S[1][4]−S[3][1]+S[1][1]=60−9−17+3=37S[3][4]-S[1][4]-S[3][1]+S[1][1]=60-9-17+3=37, which matches 2+6+5+8+9+7=372+6+5+8+9+7=37. Forgetting to add back S[1][1]S[1][1] gives 34, the corner block subtracted twice.

d dimensions: 2ᵈ corners, d passes

The proof never used that there were two dimensions. A box [l1,r1]×⋯×[ld,rd][l_1,r_1]\times\cdots\times[l_d,r_d] is a product of dd ranges, each a difference of two prefixes, so its sum expands into 2d2^d signed corners. For ε∈{0,1}d\varepsilon\in\{0,1\}^d let the corner c(ε)c(\varepsilon) take rk+1r_k+1 in coordinate kk when εk=1\varepsilon_k=1 and lkl_k when εk=0\varepsilon_k=0:

∑boxa  =  ∑ε∈{0,1}d(−1) d−∣ε∣  S[c(ε)],\sum_{\text{box}}a\;=\;\sum_{\varepsilon\in\{0,1\}^d}(-1)^{\,d-\abs{\varepsilon}}\;S\big[c(\varepsilon)\big],

where ∣ε∣\abs{\varepsilon} counts the ones in ε\varepsilon. For d=1d=1 this is P[r+1]−P[l]P[r+1]-P[l]; for d=2d=2, the four-term formula.

Building SS by the inclusion–exclusion recurrence costs 2d−12^d-1 terms per cell. There is a better way: the dd-dimensional prefix-sum operator is a product of dd commuting one-dimensional ones, Σ=Σ1Σ2⋯Σd\Sigma=\Sigma_1\Sigma_2\cdots\Sigma_d. So run an ordinary prefix sum along axis 1, then along axis 2, and so on. After the pass along axis kk, each cell holds the sum over the box that is a prefix in axes 1..k1..k and a single point in the others.

Dimension ddLookups per box queryBuild by recurrenceBuild by axis passes
12NNNN
243N3N2N2N
387N7N3N3N
dd2d2^d(2d−1)N(2^d-1)NdNdN
Additions to build a table over NN cells, and lookups per query. The query cost 2d2^d is inherent to this table; the build cost is not.

The hypercube: sums over subsets

A subset XX of {0,…,n−1}\{0,\dots,n-1\} is a point of the hypercube {0,1}n\{0,1\}^n, an nn-dimensional array of side 2, and Y⊆XY\subseteq X means Y≤XY\le X in every coordinate. So the sum over subsets, the zeta transform

F(X)=∑Y⊆Xf(Y),F(X)=\sum_{Y\subseteq X}f(Y),

is exactly a dd-dimensional prefix sum with d=nd=n. Enumerating every pair Y⊆XY\subseteq X costs 3n3^n (the Optimal lesson Subsets as Bitmasks proves it); one prefix pass per axis costs n 2n−1n\,2^{n-1} additions. Its inverse, the difference along every axis, is Möbius inversion:

f(X)=∑Y⊆X(−1)∣X∖Y∣F(Y).f(X)=\sum_{Y\subseteq X}(-1)^{\abs{X\setminus Y}}F(Y).
python
def zeta(f, n):                     # F[X] = sum of f[Y] over all Y subset of X
    F = f[:]
    for i in range(n):              # one axis of the hypercube per bit
        for X in range(1 << n):
            if X >> i & 1:
                F[X] += F[X ^ (1 << i)]
    return F

def mobius(F, n):                   # the inverse: a difference along every axis
    f = F[:]
    for i in range(n):
        for X in range(1 << n):
            if X >> i & 1:
                f[X] -= f[X ^ (1 << i)]
    return f

Each loop over bit ii is a 1-D prefix sum (or difference) along axis ii. Both run in Θ(n 2n)\Theta(n\,2^n) time, in place.

Check your understanding

For n=20n=20, how many additions does the bit-by-bit zeta transform perform?

  1. 20⋅219≈1.05×10720\cdot2^{19}\approx1.05\times10^7
  2. 320≈3.5×1093^{20}\approx3.5\times10^9
  3. 420≈1.1×10124^{20}\approx1.1\times10^{12}
  4. 220≈1.05×1062^{20}\approx1.05\times10^6
Show the answer

A. 20⋅219≈1.05×10720\cdot2^{19}\approx1.05\times10^7

Each of the 20 passes adds into the 2192^{19} masks that contain its bit: 20⋅219=10,485,76020\cdot2^{19}=10{,}485{,}760 additions, about 330 times fewer than enumerating all 3203^{20} pairs Y⊆XY\subseteq X.

Classical inclusion–exclusion is Möbius inversion on this lattice. The integers in [1,N][1,N] divisible by none of the primes p1,…,pkp_1,\dots,p_k number ∑T(−1)∣T∣⌊N/∏i∈Tpi⌋\sum_{T}(-1)^{\abs{T}}\lfloor N/\prod_{i\in T}p_i\rfloor, over all subsets TT; for N=100N=100 and the primes 2,3,52,3,5 that is 100−50−33−20+16+10+6−3=26100-50-33-20+16+10+6-3=26.

The same transforms multiply set functions: the OR-convolution h(X)=∑A∪B=Xf(A)g(B)h(X)=\sum_{A\cup B=X}f(A)g(B) satisfies ζh=ζf⋅ζg\zeta h=\zeta f\cdot\zeta g pointwise, so it costs O(n 2n)O(n\,2^n). Disjoint unions need one more idea, which Subsets as Bitmasks develops into the O(n22n)O(n^2 2^n) subset convolution.

What subtraction buys, and dynamic lower bounds

Everything so far relied on subtraction: the static range sum in dd dimensions takes O(N)O(N) preprocessing and O(2d)O(2^d) per query. Without an inverse, as for minimum and maximum, the picture changes. In one dimension a sparse table answers range minima in O(1)O(1) after O(nlog⁡n)O(n\log n) preprocessing, because min⁡\min tolerates overlapping ranges; general associative operations need other structures (see Sparse Tables & Square-Root Decomposition).

Updates change the picture again. With point updates mixed with prefix-sum queries, a static table costs O(n)O(n) per update, while a Fenwick tree (Fenwick, 1994) does both operations in O(log⁡n)O(\log n), and in O(log⁡dn)O(\log^d n) in dd dimensions. Can anyone do better?

The cell-probe model charges only for memory accesses: computation is free, and any word-RAM data structure is a cell-probe data structure. So the bound holds for every algorithm, hashing and bit tricks included. The proof idea is information transfer. Lay a random sequence of operations along a balanced binary tree over time. At each node, the queries in the right half must learn about log⁡n\log n bits of each update in the left half, so they must read Ω(1)\Omega(1) cells per operation that were written during the left half. Each read is charged to one node only, the lowest common ancestor of the times the cell was written and read, and each of the log⁡n\log n levels contributes Ω(1)\Omega(1) per operation.

Key takeaways

  • A summed-area table S[i][j]S[i][j] of top-left block sums answers any rectangle with four lookups, S[r2+1][c2+1]−S[r1][c2+1]−S[r2+1][c1]+S[r1][c1]S[r_2+1][c_2+1]-S[r_1][c_2+1]-S[r_2+1][c_1]+S[r_1][c_1], by inclusion–exclusion.
  • In dd dimensions a box query needs 2d2^d signed corners, but the table is built with dd one-dimensional passes, O(dN)O(dN), because the prefix-sum operator factors by axis.
  • Sums over subsets are prefix sums on the hypercube: the zeta transform takes n 2n−1n\,2^{n-1} additions instead of 3n3^n, and Möbius inversion, the same loops with subtraction, undoes it.
  • Static range sums are O(1)O(1) thanks to subtraction; dynamic prefix sums cost Θ(log⁡n)\Theta(\log n) per operation, a cell-probe lower bound (Pătraşcu–Demaine) that Fenwick trees meet.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A 3-D prefix table SS is built over a 100×100×100100\times100\times100 array. How many entries of SS does one box-sum query combine in general?

  1. 3
  2. 4
  3. 6
  4. 8
Show the answer

D. 8

A box is a product of three ranges, each a difference of two prefixes, so its sum expands into 23=82^3=8 signed corners.

Question 2

Why build a dd-dimensional prefix table by dd one-dimensional passes rather than by the inclusion–exclusion recurrence?

  1. The recurrence gives wrong answers for d≥3d\ge3
  2. Passes cost dNdN additions instead of (2d−1)N(2^d-1)N, because the dd-dimensional prefix sum factors into dd commuting 1-D prefix sums
  3. Passes make each query cost dd lookups instead of 2d2^d
  4. Passes avoid the need for a zero border
Show the answer

B. Passes cost dNdN additions instead of (2d−1)N(2^d-1)N, because the dd-dimensional prefix sum factors into dd commuting 1-D prefix sums

Σ=Σ1⋯Σd\Sigma=\Sigma_1\cdots\Sigma_d, and each factor is one linear pass. The table is the same either way; only the build cost differs. Queries still need 2d2^d corners.

Question 3

You computed F=ζfF=\zeta f, the sums over subsets, and need ff back. What does the inverse transform do?

  1. Run the same bit-by-bit loops with subtraction instead of addition
  2. Divide each F(X)F(X) by 2∣X∣2^{\abs{X}}
  3. Run the zeta transform a second time
  4. Enumerate supersets instead of subsets
Show the answer

A. Run the same bit-by-bit loops with subtraction instead of addition

Each pass of the zeta transform is a 1-D prefix sum along one axis; its inverse is the 1-D difference along that axis, f(X)−=f(X∖{i})f(X)\mathrel{-}=f(X\setminus\{i\}). Together the passes compute f(X)=∑Y⊆X(−1)∣X∖Y∣F(Y)f(X)=\sum_{Y\subseteq X}(-1)^{\abs{X\setminus Y}}F(Y).

Question 4

Which statement about maintaining prefix sums under point updates is true?

  1. Hashing gives O(1)O(1) time for both updates and queries
  2. The Ω(log⁡n)\Omega(\log n) lower bound holds only for comparison-based algorithms
  3. In the cell-probe model some operation needs Ω(log⁡n)\Omega(\log n) amortized time, so Fenwick trees are optimal up to constants
  4. The best possible time per operation is Θ(n)\Theta(\sqrt n)
Show the answer

C. In the cell-probe model some operation needs Ω(log⁡n)\Omega(\log n) amortized time, so Fenwick trees are optimal up to constants

Pătraşcu and Demaine proved Ω(log⁡n)\Omega(\log n) amortized per operation, even for randomized structures, in a model where computation is free. A Fenwick tree achieves O(log⁡n)O(\log n) for both.

Further reading

  • F. C. Crow, "Summed-area tables for texture mapping," Computer Graphics (Proceedings of SIGGRAPH '84) 18(3) (1984), 207–212.
  • P. Viola & M. Jones, "Rapid object detection using a boosted cascade of simple features," Proceedings of CVPR (2001).
  • G.-C. Rota, "On the foundations of combinatorial theory I. Theory of Möbius functions," Zeitschrift für Wahrscheinlichkeitstheorie und verwandte Gebiete 2 (1964), 340–368.
  • M. Pătraşcu & E. D. Demaine, "Logarithmic lower bounds in the cell-probe model," SIAM Journal on Computing 35(4) (2006), 932–963.
  • K. G. Larsen, "The cell probe complexity of dynamic range counting," Proceedings of STOC (2012).