- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 46 lines of Python from the credited upstream file 308.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class FenwickTree:2 def __init__(self, m: int, n: int):3 self.sums = [[0] * (n + 1) for _ in range(m + 1)]4 5 def add(self, row: int, col: int, delta: int) -> None:6 i = row7 while i < len(self.sums):8 j = col9 while j < len(self.sums[0]):10 self.sums[i][j] += delta11 j += FenwickTree.lowbit(j)12 i += FenwickTree.lowbit(i)13 14 def get(self, row: int, col: int) -> int:15 summ = 016 i = row17 while i > 0:18 j = col19 while j > 0:20 summ += self.sums[i][j]21 j -= FenwickTree.lowbit(j)22 i -= FenwickTree.lowbit(i)23 return summ24 25 @staticmethod26 def lowbit(i: int) -> int:27 return i & -i28 29 30class NumMatrix:31 def __init__(self, matrix: list[list[int]]):32 self.matrix = matrix33 self.tree = FenwickTree(len(matrix), len(matrix[0]))34 35 for i in range(len(matrix)):36 for j, val in enumerate(matrix[i]):37 self.tree.add(i + 1, j + 1, val)38 39 def update(self, row: int, col: int, val: int) -> None:40 self.tree.add(row + 1, col + 1, val - self.matrix[row][col])41 self.matrix[row][col] = val42 43 def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:44 return (self.tree.get(row2 + 1, col2 + 1) - self.tree.get(row1, col2 + 1) -45 self.tree.get(row2 + 1, col1) + self.tree.get(row1, col1))46