Range Sum Query 2D – Immutable
Design a NumMatrix class initialized once with an m x n integer matrix. sumRegion(row1, col1, row2, col2) must return the sum of all elements inside the rectangle whose top-left corner is (row1, col1) and bottom-right corner is (row2, col2), inclusive. Many queries will be made.
Open official problem prompt ↗Answer any rectangle-sum query on a fixed 2D grid in constant time after a single preprocessing pass.
Imagine measuring how much rain fell over a rectangular county. If you keep a running total of rainfall from the map's corner to every point, you can find any county's total by combining four corner readings instead of re-summing every cell.
- 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]]; sumRegion(2,1,4,3)
- Output
- 8
- Why
- The 3x3 block rows 2..4 and cols 1..3 sums to 2+0+1+1+0+1+0+3+0 = 8
m == matrix.lengthn == matrix[i].length1 <= m, n <= 200-10^4 <= matrix[i][j] <= 10^40 <= row1 <= row2 < m0 <= col1 <= col2 < nAt most 10^4 calls to sumRegion