Efficient Matrix Summation With O(1) Time Complexity
Create prefix sum matrix O(n*m) time, O(n*m) space. Sum of rectangle is calculated in O(row1+row2) time using prefix sum matrix.
Problem
TC: O(n*m) for creating the prefix[][] sum matrix, O(row1+row2) for calculating the sum of the given rectangle
SC: O(n*m) for using the prefix[][] sum matrix
class NumMatrix {
int prefix[][];
public NumMatrix(int[][] matrix) {
prefix = new int[matrix.length][matrix[0].length];
for(int i=0;i<matrix.length;i++){
int current = 0;
for(int j = 0;j<matrix[0].length;j++){
current+=matrix[i][j];
prefix[i][j] = current;
}
}
}
public int sumRegion(int row1, int col1, int row2, int col2) {...