Range Sum Query 2D - Immutable
Range Sum Query 2D - Immutable is LeetCode 304 (Medium). Implement a NumMatrix class for a fixed integer grid:
NumMatrix(matrix)receives the grid once.sumRegion(row1, col1, row2, col2)returns the sum of every cell in the rectangle with top-left corner(row1, col1)and bottom-right corner(row2, col2), both included.
The grid never changes, and there can be 10⁴ queries on a grid of up to 200 × 200. Adding up the cells for each query could cost 40,000 additions, 4 × 10⁸ in total, so each query must run in O(1).
- m == matrix.length
- n == matrix[i].length
- 1 <= m, n <= 200
- -10⁴ <= matrix[i][j] <= 10⁴
- 0 <= row1 <= row2 < m
- 0 <= col1 <= col2 < n
- At most 10⁴ calls will be made to sumRegion.
Intuition
Store, for every cell, the sum of the whole block from the top-left corner of the grid down to that cell. Call it pre.
Any rectangle is then one big block minus two strips plus one small block:
- Big block: everything from
(0, 0)to the bottom-right corner of the rectangle. - Minus two strips: the rows above the rectangle and the columns to its left.
- Plus the corner: the block above and to the left sits inside both strips, so it was subtracted twice. Add it back once.
Each of those four pieces is one lookup in pre, so a query costs four lookups however big the rectangle is.
Approach
Pad the table with a row and a column of zeros
Make pre of size (m + 1) × (n + 1), where pre[r][c] is the sum of rows 0..r-1 and columns 0..c-1. Row 0 and column 0 are empty blocks with sum 0, so rectangles touching the top or left edge need no special case.
Fill each cell from three neighbours
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 both contain the block above-left, so it is counted twice and subtracted once.
Answer a query with four lookups
Return pre[row2+1][col2+1] - pre[row1][col2+1] - pre[row2+1][col1] + pre[row1][col1]. The +1 on row2 and col2 comes from the padding: pre index k covers grid rows 0..k-1.
Code in Python, C++ and Java
(r, c) will hold the sum of grid rows 0..r-1 and columns 0..c-1. Row 0 and column 0 cover no cells at all, so they are 0.(0, 0) to (0, 0). The block above (0) and the block to the left (0) both include the block above-left (0), so that one is subtracted once. Add the cell itself: 3.(0, 0) to (0, 1). The block above (0) and the block to the left (3) both include the block above-left (0), so that one is subtracted once. Add the cell itself: 3.(0, 0) to (0, 2). The block above (0) and the block to the left (3) both include the block above-left (0), so that one is subtracted once. Add the cell itself: 4.(0, 0) to (1, 0). The block above (3) and the block to the left (0) both include the block above-left (0), so that one is subtracted once. Add the cell itself: 8.(0, 0) to (1, 1). The block above (3) and the block to the left (8) both include the block above-left (3), so that one is subtracted once. Add the cell itself: 14.(0, 0) to (1, 2). The block above (4) and the block to the left (14) both include the block above-left (3), so that one is subtracted once. Add the cell itself: 18.(0, 0) to (2, 0). The block above (8) and the block to the left (0) both include the block above-left (0), so that one is subtracted once. Add the cell itself: 9.(0, 0) to (2, 1). The block above (14) and the block to the left (9) both include the block above-left (8), so that one is subtracted once. Add the cell itself: 17.(0, 0) to (2, 2). The block above (18) and the block to the left (17) both include the block above-left (14), so that one is subtracted once. Add the cell itself: 21.(3, 3) is the sum of everything from the top-left of the grid to the rectangle's bottom-right corner: 21. It includes the rectangle plus the shaded cells above and to the left of it.(1, 1) is the block above-left of the rectangle, which was subtracted twice. Adding it back once leaves exactly the outlined cells: 11. Four lookups, whatever the size of the rectangle.(r, c) will hold the sum of grid rows 0..r-1 and columns 0..c-1. Row 0 and column 0 cover no cells at all, so they are 0.(0, 0) to (0, 0). The block above (0) and the block to the left (0) both include the block above-left (0), so that one is subtracted once. Add the cell itself: 1.(0, 0) to (0, 1). The block above (0) and the block to the left (1) both include the block above-left (0), so that one is subtracted once. Add the cell itself: -1.(0, 0) to (0, 2). The block above (0) and the block to the left (-1) both include the block above-left (0), so that one is subtracted once. Add the cell itself: 2.(0, 0) to (1, 0). The block above (1) and the block to the left (0) both include the block above-left (0), so that one is subtracted once. Add the cell itself: 5.(0, 0) to (1, 1). The block above (-1) and the block to the left (5) both include the block above-left (1), so that one is subtracted once. Add the cell itself: 8.(0, 0) to (1, 2). The block above (2) and the block to the left (8) both include the block above-left (-1), so that one is subtracted once. Add the cell itself: 5.(2, 3) is the sum of everything from the top-left of the grid to the rectangle's bottom-right corner: 5. It includes the rectangle plus the shaded cells above and to the left of it.(0, 1) is the block above-left of the rectangle, which was subtracted twice. Adding it back once leaves exactly the outlined cells: 0. Four lookups, whatever the size of the rectangle.Common pitfalls
Forgetting to add the corner back
return p[row2 + 1][col2 + 1] - p[row1][col2 + 1] - p[row2 + 1][col1]
return (p[row2 + 1][col2 + 1] - p[row1][col2 + 1]
- p[row2 + 1][col1] + p[row1][col1])The block above-left of the rectangle lies in both strips, so it is removed twice. For matrix = [[3, 0, 1], [5, 6, 3], [1, 2, 0]] and the query (1, 1, 2, 2), this returns 8 instead of 11: the corner cell 3 is missing.
Skipping the padding in Python
pre[r][c] = sum of rows 0..r, cols 0..c return pre[row2][col2] - pre[row1 - 1][col2] - ...
pre = [[0] * (n + 1) for _ in range(m + 1)] return p[row2 + 1][col2 + 1] - p[row1][col2 + 1] - ...
Without the zero row, a query with row1 = 0 reads pre[-1]. Python does not raise an error: index -1 is the last row, so the answer is silently wrong. C++ and Java read out of bounds instead.
Edge cases
The four lookups cancel down to that single cell's value, so no special case is needed.
row1 = col1 = 0, so three of the four lookups land in the padding and are 0. The answer is pre[m][n].
Complexity
(m + 1)(n + 1) cells once. Each query is four lookups and three additions. The largest possible sum, 200 × 200 × 10⁴ = 4 × 10⁸, fits in a 32-bit int.Range Sum Query 2D - Immutable FAQ
What if the matrix can be updated between queries?
Then a prefix table goes stale: one changed cell alters every pre entry below and to its right, up to O(m·n) work per update. That version is LeetCode 308 (Range Sum Query 2D - Mutable), usually solved with a 2D Fenwick tree in O(log m · log n) per update and query.
Can I build the table in place, without extra memory?
Yes, by overwriting matrix[r][c] with the prefix sum, but then queries need the row1 - 1 form and bounds checks, because there is no zero row. The padded copy costs O(m·n) memory and keeps the query a fixed four-term formula.