⚡Flashcard Drill➔
NeetCode #163LC-308MediumArrays & Hashing
← Back to All Problems

#163 · #308 · Range Sum Query 2D - Mutable(二维区域和检索 - 可变)

📌 Problem Statement & Constraints

Design a class supporting update(row, col, val) and sumRegion(row1, col1, row2, col2) on a 2D matrix. Constraints: 1 <= m, n <= 200; up to 10^4 calls.

💡 Core Algorithmic Approaches

  1. Keep a 2D prefix-sum table so queries are O(1).
  2. On update, write the new value into the matrix and rebuild the prefix table from the updated cell onward.
  3. The rebuild only needs to touch the suffix rectangle starting at (row, col), since earlier prefix entries are unaffected.
  4. A 2D Fenwick tree (BIT) gives O(log m * log n) per operation; the suffix rebuild is O(m * n) worst case but far simpler and fast enough at these limits.

💻 Benchmark Python3 Implementation

class NumMatrix:
    def __init__(self, matrix: List[List[int]]):
        self.matrix = matrix
        self.m = len(matrix)
        self.n = len(matrix[0])
        self.P = [[0] * (self.n + 1) for _ in range(self.m + 1)]
        for i in range(self.m):
            for j in range(self.n):
                self.P[i + 1][j + 1] = (self.P[i][j + 1] + self.P[i + 1][j]
                                        - self.P[i][j] + matrix[i][j])

    def update(self, row: int, col: int, val: int) -> None:
        self.matrix[row][col] = val
        # rebuild only the suffix rectangle affected by this cell
        for i in range(row, self.m):
            for j in range(col, self.n):
                self.P[i + 1][j + 1] = (self.P[i][j + 1] + self.P[i + 1][j]
                                        - self.P[i][j] + self.matrix[i][j])

    def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:
        return (self.P[row2 + 1][col2 + 1]
                - self.P[row1][col2 + 1]
                - self.P[row2 + 1][col1]
                + self.P[row1][col1])

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(m * n) to build, O(m * n) worst case per update, O(1) per query. A 2D Fenwick tree would give O(log m * log n) for both operations.
💾 Space Complexity
O(m * n) for the prefix table plus the matrix copy.

⚠️ Interview Pitfalls & Follow-ups

  • Rebuilding the whole prefix table on every update: correct but wasteful; only the suffix rectangle changes.
  • Getting the inclusion-exclusion signs wrong in sumRegion: the final term is + P[row1][col1].
  • Forgetting to store the matrix: the rebuild reads from it, so the updated value must be written there first.
  • Using a 1D prefix sum per row: queries spanning multiple rows would still need a row loop, giving O(m) per query.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Arrays & Hashing Problems

中文速览与面试要点

二维区域和检索 - 可变

给你一个二维矩阵 matrix,你需要处理以下两种操作: update(row, col, val) 将 matrix[row][col] 更新为 val; sumRegion(row1, col1, row2, col2) 返回左上角 (row1, col1)、右下角 (row2, col2) 的子矩阵元素之和。要求:两种操作的时间复杂度都优于 O(m · n)。约束:1 ≤ m, n ≤ 200;-1000 ≤ matrix[i][j] ≤ 1000;最多调用 10^4 次方法。

核心要点

  • 二维树状数组(标准解) :把一维 BIT 扩展到二维——每个节点维护一个二维区间和,update 与 query 均为 O(log m · log n)。
  • 为什么不用二维前缀和 :前缀和的查询是 O(1) 但更新是 O(m · n)(更新一个格子会影响其右下所有前缀和)。有更新操作时前缀和失效。
  • 为什么不用线段树 :二维线段树实现复杂、常数大;BIT 代码更短且足够。
  • BIT 核心操作 : add(i, j, v) 沿 i += i &amp; -i 、 j += j &amp; -j 更新; query(i, j) 沿 i -= i &amp; -i 、 j -= j &amp; -j 累加。
  • 容斥查询 : sumRegion = 四个 query 的组合,与 304 题一致。

常见陷阱

  • 用二维前缀和实现 update :更新单个格子需要重建其右下所有前缀和,是 O(m · n),在有大量 update 时会超时。必须用 BIT 或线段树。
  • BIT 的下标忘记 +1 :BIT 的下标从 1 开始,而输入的 row/col 从 0 开始,所有 _add 与 _prefix 的边界必须严格区分。
  • update 时直接加 val 而非差值 :BIT 中存的是增量,必须用 val − 旧值 。否则多次 update 会累加错误。
  • 忘记同步维护 self.mat :BIT 本身不保存单点值,必须额外维护原始矩阵以计算差值。

参考实现

class NumMatrix:
    def __init__(self, matrix: list[list[int]]):
        self.m = len(matrix)
        self.n = len(matrix[0]) if self.m else 0
        # BIT 下标从 1 开始,故多开一行一列
        self.bit = [[0] * (self.n + 1) for _ in range(self.m + 1)]
        self.mat = [[0] * self.n for _ in range(self.m)]
        for i in range(self.m):
            for j in range(self.n):
                self.update(i, j, matrix[i][j])

    def _add(self, i: int, j: int, v: int) -> None:
        """内部:在 BIT 上加值,i、j 为 0-based。"""
        i += 1
        j += 1
        while i <= self.m:
            jj = j
            while jj <= self.n:
                self.bit[i][jj] += v
                jj += jj & -jj
            i += i & -i

    def _prefix(self, i: int, j: int) -> int:
        """内部:前 i 行、前 j 列的和(i、j 为 1-based 数量)。"""
        s = 0
        while i > 0:
            jj = j
            while jj > 0:
                s += self.bit[i][jj]
                jj -= jj & -jj
            i -= i & -i
        return s

    def update(self, row: int, col: int, val: int) -> None:
        delta = val - self.mat[row][col]      # 只更新差值
        self.mat[row][col] = val
        self._add(row, col, delta)

    def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:
        p = self._prefix
        return (p(row2 + 1, col2 + 1) - p(row1, col2 + 1)
                - p(row2 + 1, col1) + p(row1, col1))