Problem
Given a 2D matrix matrix
, handle multiple queries of the following type:
- Calculate the sum of the elements of
matrix
inside the rectangle defined by its upper left corner(row1, col1)
and lower right corner(row2, col2)
.
Implement the NumMatrix class:
NumMatrix(int[][] matrix)
Initializes the object with the integer matrixmatrix
.int sumRegion(int row1, int col1, int row2, int col2)
Returns the sum of the elements ofmatrix
inside the rectangle defined by its upper left corner(row1, col1)
and lower right corner(row2, col2)
.
Examples
Example 1:
|
|
Solution
Method 1 - Prefix Sum
To optimise multiple calls to the sumRegion
method, we preprocess the matrix to create a prefix sum matrix. An array prefix[][]
is defined to hold the cumulative sum from (0, 0)
to each cell in the matrix.
Prefix Sum Matrix Construction
For a given cell (i, j)
in the prefix sum matrix, i.e. prefix[i][j]
, it stores the sum of elements in the rectangle from the top-left (0, 0)
to (i, j)
of the original matrix.
Now, if someone queries for sum of green region below:
As value at [0][0]
appears twice, we we have to add it back.
So, the formula to calculate prefix sum is:
|
|
This is how the formula using prefix sum looks:
Code
|
|
|
|
Complexity
- ⏰ Time complexity
- Preprocessing in constructor:
O(m * n)
, wherem
is the number of rows andn
is the number of columns. - Query:
O(1)
for each sumRegion query.
- Preprocessing in constructor:
- 🧺 Space complexity:
O(m * n)
for the prefix sum matrix.