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 matrixmatrix.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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code