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: Matrix → Rectangle SumsInput Matrix3014256321120154101710305Prefix Sum Built334810O(mn) Build TimeO(1) Query Time!Query: sumRegion(2,1,4,3)Result: Sum = 8Formula: O(1) calculationUsing prefix sum arrayMultiple queries answered instantly!
Understanding the Visualization
1
Input Matrix
2D matrix with rectangle query bounds
2
Build Prefix Sum
Pre-compute cumulative sums for instant queries
3
Query Results
Answer any rectangle sum in O(1) time
Key Takeaway
🎯 Key Insight: Pre-computing 2D prefix sums transforms expensive O(mn) rectangle queries into instant O(1) calculations
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