Range Sum Query 2D - Immutable

Given a 2D integer matrix, answer many queries asking for the sum of the elements inside a rectangle whose upper-left corner is `(row1, col1)` and lower-right corner is `(row2, col2)`, inclusive. Implement the `NumMatrix` class: - `NumMatrix(int[][] matrix)` initializes the object with the matrix. - `int sumRegion(int row1, int col1, int row2, int col2)` returns the sum of the rectangle. Each `sumRegion` call must run in O(1) time.

30:00

Range Sum Query 2D - Immutable
medium
Free written solution
Topics
Companies

Given a 2D integer matrix, answer many queries asking for the sum of the elements inside a rectangle whose upper-left corner is (row1, col1) and lower-right corner is (row2, col2), inclusive.

Implement the NumMatrix class:

  • NumMatrix(int[][] matrix) initializes the object with the matrix.
  • int sumRegion(int row1, int col1, int row2, int col2) returns the sum of the rectangle.

Each sumRegion call must run in O(1) time.

Example 1:
Input: {"commands":["NumMatrix","sumRegion","sumRegion","sumRegion"],"values":[[[[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]]],[2,1,4,3],[1,1,2,2],[1,2,2,4]]}
Output: [null,8,11,12]
Constraints:
  • m==matrix.lengthm == \text{matrix.length}

  • n==matrix[i].lengthn == \text{matrix}[i].\text{length}

  • 1≤m,n≤2001 \leq m, n \leq 200

  • −104≤matrix[i][j]≤104-10^4 \leq \text{matrix}[i][j] \leq 10^4

  • 0≤row1≤row2<m0 \leq \text{row1} \leq \text{row2} < m

  • 0≤col1≤col2<n0 \leq \text{col1} \leq \text{col2} < n

  • At most 10410^4 calls will be made to sumRegion.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"commands":["NumMatrix","sumRegion","sumRegion","sumRegion"],"values":[[[[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]]],[2,1,4,3],[1,1,2,2],[1,2,2,4]]}

Construct NumMatrix on a 5 x 5 matrix. Allocate a 6 x 6 prefix table whose top row and left column are 0: an empty rectangle sums to 0.

constructor building
sumRegion 0/3

pre[i][j] = sum of the top-left i x j block

matrix (5 x 5)

0

1

2

3

4

0

3
0
1
4
2

1

5
6
3
2
1

2

1
2
0
1
5

3

4
1
0
1
7

4

1
0
3
0
5

pre (6 x 6)

0

1

2

3

4

5

0

0
0
0
0
0
0

1

0

2

0

3

0

4

0

5

0

Gold block = what the new pre cell covers. Blue cells are added, the pink diagonal is subtracted because both blue blocks contain it.

Variables
VariableValue
m5
n5
DepthFunction Call
Stack empty
0/33