Range Sum Query 2D - Immutable
Difficulty: Medium · Pattern: Prefix Sum · LeetCode #304
Design NumMatrix, built from a 2-D integer matrix, supporting sumRegion(row1, col1, row2, col2): the sum of the rectangle with corners (row1, col1) and (row2, col2), inclusive, in O(1) per query.
Example
text
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) → 8, sumRegion(1,1,2,2) → 11, sumRegion(1,2,2,4) → 12Hints
- Let P[i][j] be the sum of the rectangle from (0,0) to (i−1, j−1).
- A rectangle sum combines four P values with inclusion–exclusion.
Approach
Build P of size (m+1)×(n+1): P[i+1][j+1] = M[i][j] + P[i][j+1] + P[i+1][j] − P[i][j]. Then the sum of the region is P[r2+1][c2+1] − P[r1][c2+1] − P[r2+1][c1] + P[r1][c1]: subtract the strips above and to the left, then add back their doubly subtracted overlap.
Complexity
Time: O(m·n) build, O(1) per query. Space: O(m·n).
Python solution
class NumMatrix:
def __init__(self, matrix):
m, n = len(matrix), len(matrix[0])
self.P = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m):
for j in range(n):
self.P[i + 1][j + 1] = matrix[i][j] + self.P[i][j + 1] + self.P[i + 1][j] - self.P[i][j]
def sumRegion(self, row1, col1, row2, col2):
P = self.P
return P[row2 + 1][col2 + 1] - P[row1][col2 + 1] - P[row2 + 1][col1] + P[row1][col1]JavaScript solution
class NumMatrix {
constructor(matrix) {
const m = matrix.length, n = matrix[0].length;
this.P = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
for (let i = 0; i < m; i++) for (let j = 0; j < n; j++)
this.P[i + 1][j + 1] = matrix[i][j] + this.P[i][j + 1] + this.P[i + 1][j] - this.P[i][j];
}
sumRegion(r1, c1, r2, c2) { const P = this.P; return P[r2 + 1][c2 + 1] - P[r1][c2 + 1] - P[r2 + 1][c1] + P[r1][c1]; }
}