Range Sum Query 2D - Immutable - Problem

Given a 2D matrix matrix, handle multiple queries of the following type:

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 class:

  • NumMatrix(int[][] matrix) Initializes the object with the integer matrix matrix.
  • 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 sumRegion works in O(1) time complexity.

Input & Output

Example 1 — Basic Rectangle Query
$ Input: matrix = [[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]], queries = [[2,1,4,3],[1,1,2,2],[1,2,2,4]]
Output: [8,11,12]
💡 Note: Query 1: Sum of rectangle from (2,1) to (4,3) = 2+0+1 + 1+0+1 + 0+3+0 = 8. Query 2: Sum from (1,1) to (2,2) = 6+3 + 2+0 = 11. Query 3: Sum from (1,2) to (2,4) = 3+2+1 + 0+1+5 = 12.
Example 2 — Single Cell Query
$ Input: matrix = [[1,2],[3,4]], queries = [[0,0,0,0],[1,1,1,1]]
Output: [1,4]
💡 Note: Query single cells: matrix[0][0] = 1 and matrix[1][1] = 4.
Example 3 — Full Matrix Query
$ Input: matrix = [[1,2],[3,4]], queries = [[0,0,1,1]]
Output: [10]
💡 Note: Sum of entire 2x2 matrix: 1+2+3+4 = 10.

Constraints

  • m == matrix.length
  • n == matrix[i].length
  • 1 ≤ m, n ≤ 200
  • -105 ≤ matrix[i][j] ≤ 105
  • 1 ≤ queries.length ≤ 104
  • 0 ≤ row1 ≤ row2 < m
  • 0 ≤ col1 ≤ col2 < n

Visualization

Tap to expand
Range Sum Query 2D - Immutable INPUT 5x5 Matrix: 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 Queries: Q1: (2,1,4,3) Q2: (1,1,2,2) Q3: (1,2,2,4) Pink = Query 2 region (row1=1,col1=1,row2=2,col2=2) ALGORITHM STEPS 1 Build Prefix Sum Pre-compute cumulative sums 2 Prefix[i][j] Formula Sum from (0,0) to (i,j) 3 Query in O(1) Inclusion-exclusion 4 Apply Formula P[r2][c2] - P[r1-1][c2] - P[r2][c1-1] + P[r1-1][c1-1] Inclusion-Exclusion: D - B - C + A = SUM Time: O(1) per query FINAL RESULT Query Results: Q1: (2,1,4,3) Sum = 2+0+1+1+0+1+0+3+0 8 Q2: (1,1,2,2) Sum = 6+3+2+0 11 Q3: (1,2,2,4) Sum = 3+2+1+0+1+5 12 Output Array: [8, 11, 12] OK - All queries solved! O(mn) preprocess, O(1) query Key Insight: Use 2D prefix sum array where prefix[i][j] = sum of all elements from (0,0) to (i-1,j-1). Any rectangular region sum can be computed in O(1) using inclusion-exclusion principle: sum(r1,c1,r2,c2) = P[r2+1][c2+1] - P[r1][c2+1] - P[r2+1][c1] + P[r1][c1] TutorialsPoint - Range Sum Query 2D - Immutable | Optimal Solution (2D Prefix Sum)
Asked in
Google 45 Amazon 35 Facebook 30 Microsoft 25
125.0K Views
Medium Frequency
~15 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen