Range Sum Query 2D - Immutable (LeetCode 304): Solution and Explanation
Build a NumMatrix that answers sumRegion(row1, col1, row2, col2), the sum of every cell in a rectangle, in constant time. The matrix never changes, so all the work can happen once in the constructor.
Intuition
Adding up a rectangle cell by cell costs its area on every call. With up to 10^4 calls on a 200 x 200 matrix that is far too slow, so the constructor should precompute something that makes each query cheap.
In one dimension, prefix sums turn a range sum into one subtraction. In two dimensions the natural object is the sum of the top-left block: let pre[i][j] be the sum of the first i rows and first j columns.
Any rectangle can be carved out of four such blocks. Start from the block that ends at the bottom-right corner, remove the strip above the rectangle and the strip to its left, and add back the small corner block that both removals took away.
Approach: Padded 2D prefix sums
- Allocate
prewithm + 1rows andn + 1columns of zeros. The extra zero row and column mean edge rectangles need no special case. - For every cell, set
pre[r+1][c+1] = matrix[r][c] + pre[r][c+1] + pre[r+1][c] - pre[r][c]. The block above and the block to the left overlap inpre[r][c], so it is subtracted once. - For
sumRegion(row1, col1, row2, col2)returnpre[row2+1][col2+1] - pre[row1][col2+1] - pre[row2+1][col1] + pre[row1][col1].
Step-by-step example
matrix = [[3,0,1,4,2],[5,6,3,2,1],[1,2,0,1,5],[4,1,0,1,7],[1,0,3,0,5]], sumRegion(2,1,4,3), sumRegion(1,1,2,2), sumRegion(1,2,2,4)
- The constructor fills a 6 x 6 table. For example pre[1][1] = 3, pre[2][2] = 6 + 5 + 3 - 0 = 14, and pre[5][5] = 58, the sum of the whole matrix.
- sumRegion(2,1,4,3): D = pre[5][4] = 38, B = pre[2][4] = 24, C = pre[5][1] = 14, A = pre[2][1] = 8. 38 - 24 - 14 + 8 = 8.
- sumRegion(1,1,2,2): pre[3][3] - pre[1][3] - pre[3][1] + pre[1][1] = 21 - 4 - 9 + 3 = 11.
- sumRegion(1,2,2,4): pre[3][5] - pre[1][5] - pre[3][2] + pre[1][2] = 36 - 10 - 17 + 3 = 12. The output is [null,8,11,12].
Code: Python, Java, C++
1class NumMatrix:
2 def __init__(self, matrix: List[List[int]]):
3 m, n = len(matrix), len(matrix[0])
4 self.pre = [[0] * (n + 1) for _ in range(m + 1)]
5 for r in range(m):
6 for c in range(n):
7 self.pre[r + 1][c + 1] = matrix[r][c] + self.pre[r][c + 1] + self.pre[r + 1][c] - self.pre[r][c]
8
9 def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:
10 p = self.pre
11 return p[row2 + 1][col2 + 1] - p[row1][col2 + 1] - p[row2 + 1][col1] + p[row1][col1]1class NumMatrix {
2 private int[][] pre;
3
4 public NumMatrix(int[][] matrix) {
5 int m = matrix.length, n = matrix[0].length;
6 pre = new int[m + 1][n + 1];
7 for (int r = 0; r < m; r++) {
8 for (int c = 0; c < n; c++) {
9 pre[r + 1][c + 1] = matrix[r][c] + pre[r][c + 1] + pre[r + 1][c] - pre[r][c];
10 }
11 }
12 }
13
14 public int sumRegion(int row1, int col1, int row2, int col2) {
15 return pre[row2 + 1][col2 + 1] - pre[row1][col2 + 1] - pre[row2 + 1][col1] + pre[row1][col1];
16 }
17}1class NumMatrix {
2public:
3 vector<vector<int>> pre;
4
5 NumMatrix(vector<vector<int>>& matrix) {
6 int m = matrix.size(), n = matrix[0].size();
7 pre.assign(m + 1, vector<int>(n + 1, 0));
8 for (int r = 0; r < m; r++) {
9 for (int c = 0; c < n; c++) {
10 pre[r + 1][c + 1] = matrix[r][c] + pre[r][c + 1] + pre[r + 1][c] - pre[r][c];
11 }
12 }
13 }
14
15 int sumRegion(int row1, int col1, int row2, int col2) {
16 return pre[row2 + 1][col2 + 1] - pre[row1][col2 + 1] - pre[row2 + 1][col1] + pre[row1][col1];
17 }
18};Time and space complexity
O(m * n) build, O(1) per query
Each prefix cell is computed once from three neighbours. Every query reads exactly four table entries.
O(m * n)
The prefix table has (m + 1) x (n + 1) entries.
Other approaches
Brute force per query (time O(m * n) per query, space O(1))
Loop over the rectangle on every call. No preprocessing, but each query costs O(m * n) in the worst case.
Row prefix sums (time O(m) per query, space O(m * n))
Keep a 1D prefix sum for each row and add up one subtraction per row of the rectangle. Simpler to derive, but a query costs O(m).
Common mistakes
- Skipping the zero padding and then writing special cases for row1 = 0 or col1 = 0. The extra row and column remove every edge case.
- Forgetting to subtract pre[r][c] while building, which counts the overlapping block twice.
- Forgetting to add pre[row1][col1] back in the query. The top-left corner is removed by both strips.
- Mixing up the off-by-one: the matrix cell (r, c) is stored at pre[r+1][c+1].
Frequently asked questions
Why does the query add pre[row1][col1] back?
The strip above the rectangle and the strip to its left both contain the block above and to the left of (row1, col1). Subtracting both strips removes that block twice, so it is added back once.
Why make the table one row and one column larger than the matrix?
The extra zero row and column represent empty blocks. With them, a rectangle touching the top or left edge uses the same formula as any other, with no bounds checks.
What is the time and space complexity of Range Sum Query 2D - Immutable?
Building the table takes O(m * n) time and space, and each sumRegion call takes O(1) time.
What if the matrix could change between queries?
Then a prefix table would need O(m * n) work per update. The mutable version is usually solved with a 2D Fenwick tree, which gives O(log m * log n) for both updates and queries.