304. Range Sum Query 2D - Immutable
Problem
Design NumMatrix(matrix) whose sumRegion(row1, col1, row2, col2) returns the sum of the rectangle with those top-left and bottom-right corners (inclusive), in O(1) per query. The matrix never changes.
Example: for the 5×5 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
Constraints: up to 200 × 200; up to 10⁴ queries.
P[r][c] = sum of the rectangle above-left of (r, c) (exclusive). Inclusion–exclusion: sum = P[r2+1][c2+1] − P[r1][c2+1] − P[r2+1][c1] + P[r1][c1].
+-----+---------+
| A | B | region = (A+B+C+D) - (A+B) - (A+C) + A
+-----+---------+
| C | [D] |
+-----+---------+
Complexity: O(m·n) build, O(1) query.
class NumMatrix:
def __init__(self, matrix: List[List[int]]):
R, C = len(matrix), len(matrix[0])
self.P = [[0] * (C + 1) for _ in range(R + 1)]
for r in range(R):
for c in range(C):
self.P[r + 1][c + 1] = matrix[r][c] + self.P[r][c + 1] + self.P[r + 1][c] - self.P[r][c]
def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:
P = self.P
return P[row2 + 1][col2 + 1] - P[row1][col2 + 1] - P[row2 + 1][col1] + P[row1][col1]
nm = NumMatrix([[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]])
assert [nm.sumRegion(2, 1, 4, 3), nm.sumRegion(1, 1, 2, 2), nm.sumRegion(1, 2, 2, 4)] == [8, 11, 12]
assert NumMatrix([[1, 2], [3, 4]]).sumRegion(0, 0, 1, 1) == 10
assert NumMatrix([[1, 2], [3, 4]]).sumRegion(1, 1, 1, 1) == 4
class NumMatrix {
private final int[][] P;
public NumMatrix(int[][] matrix) {
int R = matrix.length, C = matrix[0].length;
P = new int[R + 1][C + 1];
for (int r = 0; r < R; r++)
for (int c = 0; c < C; c++) P[r + 1][c + 1] = matrix[r][c] + P[r][c + 1] + P[r + 1][c] - P[r][c];
}
public int sumRegion(int r1, int c1, int r2, int c2) {
return P[r2 + 1][c2 + 1] - P[r1][c2 + 1] - P[r2 + 1][c1] + P[r1][c1];
}
}
type NumMatrix struct {
P [][]int // P[r][c] = sum of the r x c top-left block
}
func Constructor(matrix [][]int) NumMatrix {
R, C := len(matrix), len(matrix[0])
P := make([][]int, R+1)
for r := range P {
P[r] = make([]int, C+1)
}
for r := 0; r < R; r++ {
for c := 0; c < C; c++ {
P[r+1][c+1] = matrix[r][c] + P[r][c+1] + P[r+1][c] - P[r][c]
}
}
return NumMatrix{P: P}
}
func (this *NumMatrix) SumRegion(row1 int, col1 int, row2 int, col2 int) int {
P := this.P // inclusion-exclusion on four prefix blocks
return P[row2+1][col2+1] - P[row1][col2+1] - P[row2+1][col1] + P[row1][col1]
}