LeetCode #304 Medium

Range Sum Query 2D - Immutable

Range Sum Query 2D - Immutable is LeetCode 304 (Medium). Implement a NumMatrix class for a fixed integer grid:

  • NumMatrix(matrix) receives the grid once.
  • sumRegion(row1, col1, row2, col2) returns the sum of every cell in the rectangle with top-left corner (row1, col1) and bottom-right corner (row2, col2), both included.

The grid never changes, and there can be 10⁴ queries on a grid of up to 200 × 200. Adding up the cells for each query could cost 40,000 additions, 4 × 10⁸ in total, so each query must run in O(1).

Constraints
  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 200
  • -10⁴ <= matrix[i][j] <= 10⁴
  • 0 <= row1 <= row2 < m
  • 0 <= col1 <= col2 < n
  • At most 10⁴ calls will be made to sumRegion.
matrixprefix-sumdynamic-programming
Open on LeetCode ↗
02

Intuition

Store, for every cell, the sum of the whole block from the top-left corner of the grid down to that cell. Call it pre.

Any rectangle is then one big block minus two strips plus one small block:

  • Big block: everything from (0, 0) to the bottom-right corner of the rectangle.
  • Minus two strips: the rows above the rectangle and the columns to its left.
  • Plus the corner: the block above and to the left sits inside both strips, so it was subtracted twice. Add it back once.

Each of those four pieces is one lookup in pre, so a query costs four lookups however big the rectangle is.

03

Approach

1

Pad the table with a row and a column of zeros

Make pre of size (m + 1) × (n + 1), where pre[r][c] is the sum of rows 0..r-1 and columns 0..c-1. Row 0 and column 0 are empty blocks with sum 0, so rectangles touching the top or left edge need no special case.

2

Fill each cell from three neighbours

pre[r+1][c+1] = matrix[r][c] + pre[r][c+1] + pre[r+1][c] - pre[r][c]. The block above and the block to the left both contain the block above-left, so it is counted twice and subtracted once.

3

Answer a query with four lookups

Return pre[row2+1][col2+1] - pre[row1][col2+1] - pre[row2+1][col1] + pre[row1][col1]. The +1 on row2 and col2 comes from the padding: pre index k covers grid rows 0..k-1.

04

Code in Python, C++ and Java

▶1class NumMatrix:
▶2 def __init__(self, matrix: List[List[int]]):
▶3 m, n = len(matrix), len(matrix[0])
▶4 self.pre = [[0] * (n + 1) for _ in range(m + 1)]
▶5 for r in range(m):
▶6 for c in range(n):
▶7 self.pre[r + 1][c + 1] = (
▶8 matrix[r][c]
▶9 + self.pre[r][c + 1]
▶10 + self.pre[r + 1][c]
▶11 - self.pre[r][c]
▶12 )
▶13 
▶14 def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:
▶15 p = self.pre
▶16 return (
▶17 p[row2 + 1][col2 + 1]
▶18 - p[row1][col2 + 1]
▶19 - p[row2 + 1][col1]
▶20 + p[row1][col1]
▶21 )
gridprefix sums012030115632120012300000102030pad row 0 and column 0 with zeros
grid3 × 3
table4 × 4one extra row and column
The table is one row and one column bigger than the grid. Entry (r, c) will hold the sum of grid rows 0..r-1 and columns 0..c-1. Row 0 and column 0 cover no cells at all, so they are 0.
gridprefix sums0120301156321200123000001032030cell 3 + above 0 + left 0 − corner 0 → 3
grid cell3row 0, col 0
above + left00 + 0
corner0counted twice, removed once
new entry3
The new entry covers the grid from (0, 0) to (0, 0). The block above (0) and the block to the left (0) both include the block above-left (0), so that one is subtracted once. Add the cell itself: 3.
gridprefix sums01203011563212001230000010332030cell 0 + above 0 + left 3 − corner 0 → 3
grid cell0row 0, col 1
above + left30 + 3
corner0counted twice, removed once
new entry3
The new entry covers the grid from (0, 0) to (0, 1). The block above (0) and the block to the left (3) both include the block above-left (0), so that one is subtracted once. Add the cell itself: 3.
gridprefix sums012030115632120012300000103342030cell 1 + above 0 + left 3 − corner 0 → 4
grid cell1row 0, col 2
above + left30 + 3
corner0counted twice, removed once
new entry4
The new entry covers the grid from (0, 0) to (0, 2). The block above (0) and the block to the left (3) both include the block above-left (0), so that one is subtracted once. Add the cell itself: 4.
gridprefix sums0120301156321200123000001033420830cell 5 + above 3 + left 0 − corner 0 → 8
grid cell5row 1, col 0
above + left33 + 0
corner0counted twice, removed once
new entry8
The new entry covers the grid from (0, 0) to (1, 0). The block above (3) and the block to the left (0) both include the block above-left (0), so that one is subtracted once. Add the cell itself: 8.
gridprefix sums012030115632120012300000103342081430cell 6 + above 3 + left 8 − corner 3 → 14
grid cell6row 1, col 1
above + left113 + 8
corner3counted twice, removed once
new entry14
The new entry covers the grid from (0, 0) to (1, 1). The block above (3) and the block to the left (8) both include the block above-left (3), so that one is subtracted once. Add the cell itself: 14.
gridprefix sums01203011563212001230000010334208141830cell 3 + above 4 + left 14 − corner 3 → 18
grid cell3row 1, col 2
above + left184 + 14
corner3counted twice, removed once
new entry18
The new entry covers the grid from (0, 0) to (1, 2). The block above (4) and the block to the left (14) both include the block above-left (3), so that one is subtracted once. Add the cell itself: 18.
gridprefix sums012030115632120012300000103342081418309cell 1 + above 8 + left 0 − corner 0 → 9
grid cell1row 2, col 0
above + left88 + 0
corner0counted twice, removed once
new entry9
The new entry covers the grid from (0, 0) to (2, 0). The block above (8) and the block to the left (0) both include the block above-left (0), so that one is subtracted once. Add the cell itself: 9.
gridprefix sums01203011563212001230000010334208141830917cell 2 + above 14 + left 9 − corner 8 → 17
grid cell2row 2, col 1
above + left2314 + 9
corner8counted twice, removed once
new entry17
The new entry covers the grid from (0, 0) to (2, 1). The block above (14) and the block to the left (9) both include the block above-left (8), so that one is subtracted once. Add the cell itself: 17.
gridprefix sums0120301156321200123000001033420814183091721cell 0 + above 18 + left 17 − corner 14 → 21
grid cell0row 2, col 2
above + left3518 + 17
corner14counted twice, removed once
new entry21
The new entry covers the grid from (0, 0) to (2, 2). The block above (18) and the block to the left (17) both include the block above-left (14), so that one is subtracted once. Add the cell itself: 21.
gridprefix sums0120301156321200123000001033420814183091721whole block to the bottom-right corner → 21
query(1, 1, 2, 2)
big block21entry (3, 3)
The outlined rectangle is the query. Entry (3, 3) is the sum of everything from the top-left of the grid to the rectangle's bottom-right corner: 21. It includes the rectangle plus the shaded cells above and to the left of it.
gridprefix sums0120301156321200123000001033420814183091721minus the strip above, 4, and the strip left, 9
strip above4entry (1, 3)
strip left9entry (3, 1)
so far8
The rows above the rectangle add up to 4. The columns to its left add up to 9. Both are subtracted, leaving 8. But the cells above-left of the rectangle were in both strips, so they were taken off twice.
gridprefix sums0120301156321200123000001033420814183091721add back the corner block (3) → answer 11
corner3entry (1, 1)
sumRegion1121 − 4 − 9 + 3
Entry (1, 1) is the block above-left of the rectangle, which was subtracted twice. Adding it back once leaves exactly the outlined cells: 11. Four lookups, whatever the size of the rectangle.
05

Common pitfalls

Forgetting to add the corner back

✗ Wrong
return p[row2 + 1][col2 + 1] - p[row1][col2 + 1] - p[row2 + 1][col1]
✓ Right
return (p[row2 + 1][col2 + 1] - p[row1][col2 + 1]
        - p[row2 + 1][col1] + p[row1][col1])

The block above-left of the rectangle lies in both strips, so it is removed twice. For matrix = [[3, 0, 1], [5, 6, 3], [1, 2, 0]] and the query (1, 1, 2, 2), this returns 8 instead of 11: the corner cell 3 is missing.

Skipping the padding in Python

✗ Wrong
pre[r][c] = sum of rows 0..r, cols 0..c
return pre[row2][col2] - pre[row1 - 1][col2] - ...
✓ Right
pre = [[0] * (n + 1) for _ in range(m + 1)]
return p[row2 + 1][col2 + 1] - p[row1][col2 + 1] - ...

Without the zero row, a query with row1 = 0 reads pre[-1]. Python does not raise an error: index -1 is the last row, so the answer is silently wrong. C++ and Java read out of bounds instead.

06

Edge cases

One cell, row1 = row2 and col1 = col2

The four lookups cancel down to that single cell's value, so no special case is needed.

The whole grid

row1 = col1 = 0, so three of the four lookups land in the padding and are 0. The answer is pre[m][n].

07

Complexity

Time
O(m·n) build, O(1) per query
Space
O(m·n)
The constructor fills each of the (m + 1)(n + 1) cells once. Each query is four lookups and three additions. The largest possible sum, 200 × 200 × 10⁴ = 4 × 10⁸, fits in a 32-bit int.
08

Range Sum Query 2D - Immutable FAQ

What if the matrix can be updated between queries?

Then a prefix table goes stale: one changed cell alters every pre entry below and to its right, up to O(m·n) work per update. That version is LeetCode 308 (Range Sum Query 2D - Mutable), usually solved with a 2D Fenwick tree in O(log m · log n) per update and query.

Can I build the table in place, without extra memory?

Yes, by overwriting matrix[r][c] with the prefix sum, but then queries need the row1 - 1 form and bounds checks, because there is no zero row. The padded copy costs O(m·n) memory and keeps the query a fixed four-term formula.