SDE & MLE Prep

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]