# 308 Range Sum Query 2D - Mutable

Given a 2D matrixmatrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1,col1) and lower right corner (row2,col2).

![Range Sum Query 2D](https://leetcode.com/static/images/courses/range_sum_query_2d.png)\
The above rectangle (with the red border) is defined by (row1, col1) =**(2, 1)**&#x61;nd (row2, col2) =**(4, 3)**, which contains sum =**8**.

**Example:**

```
Given 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
update(3, 2, 2)
sumRegion(2, 1, 4, 3) -> 10
```

**Note:**&#x20;

1. The matrix is only modifiable by the update function.
2. You may assume the number of calls to update and sumRegion function is distributed evenly.
3. You may assume that row1 ≤ row2 and col1 ≤ col2

**The Idea:** The general idea is to only accumulate on a row or column basis so that we only have to operate on the basis of either just rows or columns.![](/files/-LoJIkfkjgkjYcEsb8hN)

**Complexity:** O(n) time for both update and sum, and O(n) extra space where n is the number of columns

```python
import numpy as np


class NumMatrix:
    def __init__(self, matrix):
        """
        initialize your data structure here.
        :type matrix: List[List[int]]
        """
        self.d = matrix
        for row in matrix:
            NumMatrix.cum_sum(row)

    @staticmethod
    def cum_sum(row):
        for i in range(1, len(row)):
            row[i] += row[i-1]

    def update(self, row, col, val):
        """
        update the element at matrix[row,col] to val.
        :type row: int
        :type col: int
        :type val: int
        :rtype: void
        """
        # this is the old cdf
        cdf = self.d[row]

        # can build pdf from the cdf and properly insert value
        prev = 0
        pdf = []
        for row_elm in cdf:
            pdf.append(row_elm - prev)
            prev = row_elm
        pdf[col] = val

        # now update the old pdf
        for i in range(1, len(pdf)):
            pdf[i] += pdf[i-1]
        self.d[row] = pdf

    def sumRegion(self, row1, col1, row2, col2):
        """
        sum of elements matrix[(row1,col1)..(row2,col2)], inclusive.
        :type row1: int
        :type col1: int
        :type row2: int
        :type col2: int
        :rtype: int
        """

        # integral[5, 10] in discrete -> F[10] - F[5-1]
        # but treat this on a 2 dimensional scale
        right_sum, left_sum = 0, 0
        for i in range(row1, row2+1):
            right_sum += self.d[i][col2]
        if col1 - 1 >= 0:
            for i in range(row1, row2 + 1):
                left_sum += self.d[i][col1 - 1]
        return right_sum - left_sum


# Your NumMatrix object will be instantiated and called as such:
# obj = NumMatrix(matrix)
# obj.update(row,col,val)
# param_2 = obj.sumRegion(row1,col1,row2,col2)

obj = 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]])
print(obj.sumRegion(1,1,3,3))
print(obj.sumRegion(2,2,3,3))
print(obj.update(2,2,100))
print(obj.sumRegion(2,2,3,3))
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://maksimdan.gitbook.io/interview-practice-problems/leetcode_sessions/308-range-sum-query-2d-mutable.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
