Given a 2D matrix
-
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(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 of matrix inside the rectangle defined by its upper left corner(row1, col1) and lower right corner(row2, col2) .
You must design an algorithm where
"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]]
"sumRegion" : [2, 1, 4, 3]
"sumRegion" : [1, 1, 2, 2]
"sumRegion" : [1, 2, 2, 4]
Output:
Operation 1 "sumRegion" : 8
Operation 2 "sumRegion" : 11
Operation 3 "sumRegion" : 12
Explanation: Matrix grid will look like below

numMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle)
numMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle)
Constraints:
m == matrix.length n == matrix[i].length 1 <= m, n <= 200 -104 <= matrix[i][j] <= 104 0 <= row1 <= row2 < m 0 <= col1 <= col2 < n - At most
104 calls will be made tosumRegion .
Contents
Solution 1 - Prepare prefix-sum as part of constructor initialization
This problem is similar to
In this approach, we are going to pre compute prefix sum inside constructor, so that we can return
Prefix sum implementation steps:
The way we will built prefix sum will be similar to building prefix-sum for a 1D array, but we will slightly change for 2D array, that is
prefix sum at row
For example, consider the below problem, and we want to compute prefix-sum at row
Then we would be taking the sum from the row above, plus the column before. As highlighted in below diagram.
When we do that,we will be double counting the element diagonally on left side, because element
So, the generic formula for calculating the prefix sum at index
sumRegion implementation steps:
Once the prefix sum array is computed, then we will get the
From the same example we computed prefix sum above, let's compute the
So, from the cell
But, notice that both cells at
So, the result is
Generic formula calculating the
Complexity Analysis:
Time complexity: O(m *n) where
Space complexity: O(m *n ) - space used by the prefix sum array.
Above implementations source code can be found at