LeetCode 307 Range Sum Query - Mutable - Implementation

The approach

Here's the solution:

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

    function sumRegion(r1, c1, r2, c2):
        return self.prefix[r2+1][c2+1] - self.prefix[r1][c2+1] - self.prefix[r2+1][c1] + self.prefix[r1][c1]

O(logn)O(\log n) time, O(n)O(n) space per query or update.