Range Sum Query 2D - Immutable - Problem
Range Sum Query 2D - Immutable
Imagine you're working with a 2D grid of numbers and need to efficiently answer multiple queries about rectangular regions. Given a 2D matrix, you need to handle multiple queries where each query asks for the sum of all elements within a specific rectangle.
๐ฏ Your Task:
Implement the
โข
โข
โก Challenge: The
Example:
Imagine you're working with a 2D grid of numbers and need to efficiently answer multiple queries about rectangular regions. Given a 2D matrix, you need to handle multiple queries where each query asks for the sum of all elements within a specific rectangle.
๐ฏ Your Task:
Implement the
NumMatrix class with:โข
NumMatrix(int[][] matrix) - Initialize with the given matrixโข
sumRegion(int row1, int col1, int row2, int col2) - Return sum of rectangle from top-left (row1, col1) to bottom-right (row2, col2)โก Challenge: The
sumRegion method must run in O(1) time complexity!Example:
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]]sumRegion(2,1,4,3) should return 8 (sum of the highlighted rectangle) Input & Output
example_1.py โ 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 = [sumRegion(2,1,4,3), sumRegion(1,1,2,2), sumRegion(1,2,1,4)]
โบ
Output:
[8, 11, 6]
๐ก Note:
First query sums rectangle from (2,1) to (4,3): 2+0+1+1+0+1+0+3+0 = 8. Second query sums (1,1) to (2,2): 6+3+2+0 = 11. Third query sums (1,2) to (1,4): 3+2+1 = 6.
example_2.py โ Single Cell Query
$
Input:
matrix = [[1,2,3],[4,5,6],[7,8,9]]
query = sumRegion(1,1,1,1)
โบ
Output:
5
๐ก Note:
Query asks for sum of single cell at (1,1), which contains value 5.
example_3.py โ Full Matrix Query
$
Input:
matrix = [[1,2],[3,4]]
query = sumRegion(0,0,1,1)
โบ
Output:
10
๐ก Note:
Query asks for sum of entire 2x2 matrix: 1+2+3+4 = 10.
Visualization
Tap to expand
Understanding the Visualization
1
Build Prefix Matrix
Create a matrix where prefix[i][j] = sum of all elements from (0,0) to (i-1,j-1)
2
Apply Formula
For any rectangle, use: Total Area - Left Excess - Top Excess + Corner Overlap
3
Get O(1) Result
Rectangle sum = prefix[row2+1][col2+1] - prefix[row1][col2+1] - prefix[row2+1][col1] + prefix[row1][col1]
Key Takeaway
๐ฏ Key Insight: By preprocessing with 2D prefix sums, we transform expensive rectangle queries into simple O(1) arithmetic using the inclusion-exclusion principle!
Time & Space Complexity
Time Complexity
O(m*n)
O(m*n) for preprocessing, O(1) for each query
โ Linear Growth
Space Complexity
O(m*n)
Additional space for the prefix sum matrix
โก Linearithmic Space
Constraints
- m == matrix.length
- n == matrix[i].length
- 1 โค m, n โค 200
- -105 โค matrix[i][j] โค 105
- 0 โค row1 โค row2 < m
- 0 โค col1 โค col2 < n
- At most 104 calls will be made to sumRegion
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code