Range Sum Query 2D - Immutable - 2D Prefix Sum [JS]

Description 

Solution: 2D Prefix Sum

Prefix sum over the matrix, where sum[i][j] = sum of the rectangle with left top corner at [0][0] and bottom right corner at[i][j].
Note: Offset each row and column by +1 so that we don't have to deal with going out of bounds.

Time Complexity: runtime 644ms

  • initialization: O(mn)
  • sumRegion: O(1)

Space Complexity: O(mn) 84.4MB

var NumMatrix = function(matrix) {
  let m = matrix.length, n = matrix[0].length;
  this.sum = Array(m + 1).fill(0).map(() => Array(n + 1).fill(0));
  for (let i = 0; i < m; i++) {
    for (let j = 0; j < n; j++) {
      // left corner counted twice, remove from total sum
      this.sum[i + 1][j + 1] = matrix[i][j] + this.sum[i + 1][j] + this.sum[i][j + 1] - this.sum[i][j];
    }
  }
};

NumMatrix.prototype.sumRegion = function(row1, col1, row2, col2) {
  // right bottom corner - left bottom corner - right top corner + left top corner (left corner subtracted twice, add one back)
  return this.sum[row2 + 1][col2 + 1] - this.sum[row2 + 1][col1] - this.sum[row1][col2 + 1] + this.sum[row1][col1];
};

javascript

Comments

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]