Skip to problem
←

2D Range Sum Queries

Medium 0 attempts

Implement NumMatrix to answer repeated sum queries on a fixed rectangular matrix.

  • new NumMatrix(matrix) prepares the matrix for queries. Its values do not change afterward.
  • sumRegion(r1, c1, r2, c2) returns the sum of cells from top-left corner (r1, c1) through bottom-right corner (r2, c2), including both corners and every cell between them.

Rows and columns are zero-indexed. All query coordinates are valid and ordered. Queries may cover one cell, one row, one column, or the whole matrix; negative and zero values are included normally. Aim for constant time per query after preprocessing.

For matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]], sumRegion(1, 1, 2, 2) returns 5 + 6 + 8 + 9 = 28.

Examples provide constructorArgs = [matrix] and a list of method calls. Each example creates a fresh instance; its output lists the query results in call order.

Function contract

Implement the class NumMatrix. Fixtures contain constructor arguments and a list of [method, ...arguments] calls. Each fixture starts with a fresh instance.

Output: Each sumRegion call returns the inclusive rectangle sum. The displayed array lists these results in call order.

Example 1

Input
constructorArgs = [[[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]]]
operations = [["sumRegion",2,1,4,3],["sumRegion",1,1,2,2],["sumRegion",1,2,2,4]]
Output
[8,11,12]

Example 2

Input
constructorArgs = [[[5]]]
operations = [["sumRegion",0,0,0,0]]
Output
[5]
Visual Aid
Both corners are included
Inclusive rectangle sumA 3 by 3 matrix contains 1 through 9 in row order. The outlined bottom-right 2 by 2 region contains 5, 6, 8, and 9, summing to 28.001231145622789Rows 1–2, columns 1–2 · sum = 28

The selected rectangle includes four cells, not just its boundary coordinates.

Constraints
  • 1 <= m, n <= 200
  • -10^4 <= matrix[i][j] <= 10^4
  • At most 10^4 calls to sumRegion
  • 0 <= r1 <= r2 < m and 0 <= c1 <= c2 < n for every query.

Padded 2D Prefix Sums

Let prefix[r][c] store the sum of matrix rows before r and columns before c. An extra all-zero row and column make boundary queries work without special cases.

Build each entry from the current cell plus the prefix above and the prefix to the left, subtracting their overlapping top-left area once.

For a query, start with the prefix through (r2, c2). Subtract the area above r1 and the area left of c1. Their overlap was subtracted twice, so add it back. The r2 + 1 and c2 + 1 indices convert inclusive query endpoints into the prefix table's exclusive boundaries.

The constructor stores the prefix table once. Each query reads four entries without changing the matrix or table.

javascript
class NumMatrix {
  constructor(matrix) {
    const m = matrix.length,
      n = matrix[0].length;
    this.prefix = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
    for (let i = 1; i <= m; i++)
      for (let j = 1; j <= n; j++)
        this.prefix[i][j] =
          matrix[i - 1][j - 1] +
          this.prefix[i - 1][j] +
          this.prefix[i][j - 1] -
          this.prefix[i - 1][j - 1];
  }
  sumRegion(r1, c1, r2, c2) {
    return (
      this.prefix[r2 + 1][c2 + 1] -
      this.prefix[r1][c2 + 1] -
      this.prefix[r2 + 1][c1] +
      this.prefix[r1][c1]
    );
  }
}

Time: O(1) per query, O(mn) init | Space: O(mn)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript