2D Prefix Sum Matrix: Submatrix Queries in $O(1)$ Time
Answering submatrix sum queries naively by iterating over cells takes $O(R \cdot C)$ time per query, where $R$ and $C$ are the submatrix row and column dimensions.
By precomputing a 2D Prefix Sum Table (also known as a summed-area table) in $O(M \cdot N)$ time, we can answer any rectangular range sum query $(r_1, c_1)$ to $(r_2, c_2)$ in $O(1)$ time using the Principle of Inclusion-Exclusion.
Core Formula Derivation
1. Precomputing the Prefix Matrix
Let $P[i][j]$ represent the sum of all elements inside the bounding box from top-left $(0, 0)$ down to $(i-1, j-1)$ using 1-based indexing to eliminate boundary checks:
$$P[i][j] = \sum_{r=0}^{i-1} \sum_{c=0}^{j-1} \text{matrix}[r][c]$$
To compute $P[i][j]$ from previously calculated adjacent cells: $$P[i][j] = \text{matrix}[i-1][j-1] + P[i-1][j] + P[i][j-1] - P[i-1][j-1]$$
- Add
matrix[i-1][j-1]: The value of the current individual cell. - Add
P[i-1][j]: The complete area directly above. - Add
P[i][j-1]: The complete area directly to the left. - Subtract
P[i-1][j-1]: The top-left diagonal overlap that was added twice.
2. Querying Any Region $[r_1, c_1]$ to $[r_2, c_2]$
Given the 0-indexed corners of a query submatrix where $(r_1, c_1)$ is top-left and $(r_2, c_2)$ is bottom-right, map them to 1-based coordinates:
- Bottom-right bound: $(r_2 + 1, c_2 + 1)$
- Top bound to subtract: row $r_1$
- Left bound to subtract: column $c_1$
$$\text{Sum} = P[r_2 + 1][c_2 + 1] - P[r_1][c_2 + 1] - P[r_2 + 1][c_1] + P[r_1][c_1]$$
- $P[r_2 + 1][c_2 + 1]$: The total area from $(0, 0)$ to $(r_2, c_2)$.
- $- P[r_1][c_2 + 1]$: Subtracts the area strictly above the desired submatrix.
- $- P[r_2 + 1][c_1]$: Subtracts the area strictly to the left of the desired submatrix.
- $+ P[r_1][c_1]$: Adds back the top-left intersection that was subtracted twice.
Visual Matrix Coordinate Layout
0 c1 c2 N
0 +---------+-------------+-------------+
| | | |
| + P | - P | |
| [r1][c1]| [r1][c2+1] | |
r1 +---------+-------------+-------------+
| | ########### | |
| - P | # TARGET # | |
| [r2+1] | # REGION # | |
| [c1] | ########### | |
r2 +---------+-------------+-------------+
| | Total: |
| | P[r2+1] |
| | [c2+1] |
M +-----------------------+-------------+
Implementation (C++ and Python)
C++ Implementation
#include <vector>
class NumMatrix {
private:
std::vector<std::vector<int>> prefix;
public:
NumMatrix(const std::vector<std::vector<int>>& matrix) {
if (matrix.empty() || matrix[0].empty()) return;
int m = matrix.size();
int n = matrix[0].size();
// 1-based prefix table of size (m + 1) x (n + 1)
prefix.assign(m + 1, std::vector<int>(n + 1, 0));
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
prefix[i][j] = matrix[i - 1][j - 1]
+ prefix[i - 1][j]
+ prefix[i][j - 1]
- prefix[i - 1][j - 1];
}
}
}
int sumRegion(int r1, int c1, int r2, int c2) {
// Query evaluated in O(1) time
return prefix[r2 + 1][c2 + 1]
- prefix[r1][c2 + 1]
- prefix[r2 + 1][c1]
+ prefix[r1][c1];
}
};
Python Implementation
class NumMatrix:
def __init__(self, matrix: list[list[int]]):
if not matrix or not matrix[0]:
return
m, n = len(matrix), len(matrix[0])
# Construct (m + 1) x (n + 1) prefix matrix initialized with 0
self.prefix = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
self.prefix[i][j] = (
matrix[i - 1][j - 1]
+ self.prefix[i - 1][j]
+ self.prefix[i][j - 1]
- self.prefix[i - 1][j - 1]
)
def sum_region(self, r1: int, c1: int, r2: int, c2: int) -> int:
# Query evaluated in O(1) time
return (
self.prefix[r2 + 1][c2 + 1]
- self.prefix[r1][c2 + 1]
- self.prefix[r2 + 1][c1]
+ self.prefix[r1][c1]
)
Complexity Analysis
| Phase | Time Complexity | Space Complexity | Details |
|---|---|---|---|
| Preprocessing / Constructor | $O(M \cdot N)$ | $O(M \cdot N)$ | Iterates through each cell in the $M \times N$ matrix once, taking constant operations per cell. |
Range Query (sumRegion) |
$O(1)$ | $O(1)$ | Performs exactly 3 arithmetic lookups and operations regardless of submatrix area. |
Important Practical Edge Cases
- 1-Based Padding: Sizing the prefix table to $(M + 1) \times (N + 1)$ initialized to zeros completely eliminates
if (r1 == 0)orif (c1 == 0)out-of-bounds conditionals. - Overflow Protection: If summing large matrix inputs where values can approach $10^9$, values inside
prefixcan exceed standard 32-bit signed integer limits ($2^{31}-1$). In C/C++, defineprefixusinglong long/int64_telements to prevent silent integer overflow.
