308. Range Sum Query 2D - Mutable

Given a 2D matrix matrix, 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 The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (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:

  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.

// Binary Index Tree
class NumMatrix {
public:
    NumMatrix(vector<vector<int>> matrix) { // time: O(mn*log(mn)); space: O(mn)
        if (matrix.empty() || matrix[0].empty()) return;
        int m = matrix.size(), n = matrix[0].size();
        BIT = vector<vector<int> >(m + 1, vector<int>(n + 1, 0));
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                update(i, j, matrix[i][j]);
            }
        }
    }
    
    void update(int row, int col, int val) { // time: O(log(mn))
        int orig = getSum(row + 1, col + 1) - getSum(row, col + 1) - getSum(row + 1, col) + getSum(row, col);
        int diff = val - orig;
        for (int i = row + 1; i < BIT.size(); i += (i & -i)) {
            for (int j = col + 1; j < BIT[0].size(); j += (j & -j)) {
                BIT[i][j] += diff;
            }
        }
    }
    
    int getSum(int row, int col) { // time: O(log(mn))
        int sum = 0;
        for (int i = row; i > 0; i -= (i & -i)) {
            for (int j = col; j > 0; j -= (j & -j)) {
                sum += BIT[i][j];
            }
        }
        return sum;
    }
    
    int sumRegion(int row1, int col1, int row2, int col2) {
        return getSum(row2 + 1, col2 + 1) - getSum(row1, col2 + 1) - getSum(row2 + 1, col1) + getSum(row1, col1);
    }
    vector<vector<int> > BIT;
};
303. Range Sum Query - Immutable304. Range Sum Query 2D - Immutable307. Range Sum Query - Mutable

Last updated

Was this helpful?