Practice/Moloco/Leetcode 308. Range Sum Query 2D - Mutable
CodingMust
Design and implement a data structure that efficiently handles a 2D matrix with two key operations:
The data structure must handle many interleaved update and query operations efficiently. A naive approach that recalculates sums or stores precomputed prefix sums would be too slow for frequent updates.
Your task is to implement the NumMatrix class with the following methods:
NumMatrix(matrix): Initializes the object with the integer matrix matrixupdate(row, col, val): Updates the value of the cell at position (row, col) to valsumRegion(row1, col1, row2, col2): Returns the sum of the elements in the rectangle defined by its top-left corner (row1, col1) and bottom-right corner (row2, col2) (inclusive)NumMatrix class constructor to initialize with a 2D matrixupdate method to modify individual cells efficientlysumRegion method to calculate rectangular region sums efficientlyupdate and sumRegion combinedExample 1:
` Input: ["NumMatrix", "sumRegion", "update", "sumRegion"] [[[[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]]], [2, 1, 4, 3], [3, 2, 2], [2, 1, 4, 3]]
Output: [null, 8, null, 10]
Explanation: NumMatrix numMatrix = new 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]]); numMatrix.sumRegion(2, 1, 4, 3); // returns 8 (sum of region with corners (2,1) and (4,3)) numMatrix.update(3, 2, 2); // matrix[3][2] becomes 2 numMatrix.sumRegion(2, 1, 4, 3); // returns 10 (same region, but value at (3,2) changed from 0 to 2) `
Example 2:
` Input: ["NumMatrix", "sumRegion", "update", "sumRegion"] [[[[1, 2], [3, 4]]], [0, 0, 1, 1], [0, 0, 5], [0, 0, 1, 1]]
Output: [null, 10, null, 14]
Explanation: The initial sum of the entire 2×2 matrix is 1+2+3+4 = 10. After updating position (0,0) from 1 to 5, the sum becomes 5+2+3+4 = 14. `