Introduction
The 2D Prefix Sum technique extends the 1D prefix sum to matrices, enabling range sum queries after preprocessing.
Problem: Given an grid, answer queries asking for the sum of a rectangular submatrix.
Naive approach: For each query, iterate over the submatrix. Time: .
With 2D prefix sums: Preprocess in , answer each query in . Total: .
Applications:
- Image processing (box blur, integral images)
- Game development (terrain analysis)
- Competitive programming (range queries on grids)
Building the Prefix Sum
Define as the sum of all elements in the rectangle from to .
Formula:
We add the cell value, plus the prefix sum above, plus the prefix sum to the left, then subtract the overlap (which was counted twice).
function build_prefix(grid):
n, m = dimensions of grid
P = (n+1) x (m+1) array of zeros // 1-indexed with padding
for i from 1 to n:
for j from 1 to m:
P[i][j] = grid[i][j] + P[i-1][j] + P[i][j-1] - P[i-1][j-1]
return P
Time: , Space:
Querying a Submatrix
To find the sum of the rectangle from to :
Formula:
Intuition: Start with the entire rectangle from to . Subtract the region above and the region to the left. Add back the corner (subtracted twice).
function query(P, r1, c1, r2, c2):
return P[r2][c2] - P[r1-1][c2] - P[r2][c1-1] + P[r1-1][c1-1]
Time per query:
Visual Example
Grid:
Prefix sum array (with zero padding):
Query: Sum of to
✓
Verification:
Common Mistakes
1. Off-by-one errors with indexing
Use 1-indexed prefix sums with a padding row/column of zeros. This avoids special cases for or .
2. Integer overflow
With and values up to , the maximum sum is . Use 64-bit integers.
3. Confusing row/column order
Be consistent: means row , column . Some problems use which might mean column , row .
4. Forgetting the double subtraction
When building: subtract (counted twice). When querying: add (subtracted twice).
Complexity Summary:
- Preprocessing:
- Per query:
- Total: