Problem
Given a 2D matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2). And the elements of the matrix could be changed.
You have to implement three functions:
NumMatrix(matrix)
The constructor.sumRegion(row1, col1, row2, col2)
Return the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).update(row, col, val)
Update the element at (row, col) toval
.
- The matrix is only modifiable by
update
. - You may assume the number of calls to update and sumRegion function is distributed evenly.
- You may assume that row1 ≤ row2 and col1 ≤ col2.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 - Using Fenwick Tree (Binary Indexed Tree)
This problem requires efficiently computing the sum of a sub-rectangle while allowing updates to individual matrix elements. Here’s how we approach the solution:
- To handle updates efficiently, we’ll use a Fenwick Tree (Binary Indexed Tree) for 2D matrices. Fenwick Trees are ideal for problems requiring modification and querying in logarithmic time.
- We maintain an auxiliary array that helps compute prefix sums in 2D.
- The matrix can be updated using the
update
function, and the sum of a sub-rectangle can be acquired with thesumRegion
function using methods derived from prefix sums.
Steps
- Constructor (
NumMatrix
):- We initialise the data structures (
matrix
,tree
) and build the Fenwick Tree based on the initial values of the given matrix.
- We initialise the data structures (
- Update Function (
update
):- When an element (row, col) is updated, the difference between the new value and the current value is propagated into the Fenwick Tree.
- Sum Region Function (
sumRegion
):- Compute the sum of the rectangle by querying prefix sums from the Fenwick Tree.
Code
|
|
|
|
Complexity
- ⏰ Time complexity
- Initialisation (
NumMatrix
): Building the Fenwick Tree:O(rows * cols * log(rows) * log(cols))
- Update (
update
): Updating involves propagating the difference in the Fenwick Tree:O(log(rows) * log(cols))
. - Query (
sumRegion
): Fetch prefix sums:O(log(rows) * log(cols))
.
- Initialisation (
- 🧺 Space complexity:
O(rows * cols)
for using data structures (tree
andmatrix
):O(rows * cols)
.