Python 3.11+
Independent Python lists are required for prefix rows; multiplying a list of one row aliases mutable rows rather than making a grid.
Verify in Python docs(opens in a new tab)Store each top-left matrix rectangle in a padded grid, then cancel two outside strips and restore their overlap. The construction and query formulas use the same half-open row and column boundaries.
1 practice exercise5 interview problems
Recognize it when Many sums are requested for rectangles of one unchanged rectangular matrix.
Checking your account…
The one-dimensional prefix identity generalizes to two axes. prefix[r][c] owns the origin rectangle whose rows are before r and columns before c. Add a zero row and a zero column so an edge rectangle can subtract an empty strip without a special negative index.
The region above a cell and the region to its left overlap in their top-left corner. Adding both counts that corner twice, so construction subtracts it once before adding the original cell. Each row of the Python prefix grid must be independently allocated; shared rows would change supposedly finished boundaries together.
def prefix_grid(matrix):
if not matrix:return [[0]]
rows,cols=len(matrix),len(matrix[0]);prefix=[[0]*(cols+1) for _ in range(rows+1)]
for row in range(rows):
for col in range(cols):prefix[row+1][col+1]=matrix[row][col]+prefix[row][col+1]+prefix[row+1][col]-prefix[row][col]
return prefixImplement prefix_grid(matrix). matrix is rectangular with equal row widths. Return a rows+1 by cols+1 padded grid where each boundary stores the sum above and left; empty outer input returns [[0]].
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
def prefix_grid(matrix):
if not matrix:return [[0]]
rows,cols=len(matrix),len(matrix[0]);prefix=[[0]*(cols+1) for _ in range(rows+1)]
for row in range(rows):
for col in range(cols):prefix[row+1][col+1]=matrix[row][col]+prefix[row][col+1]+prefix[row+1][col]-prefix[row][col]
return prefixThe existing builder on [[2, 1], [3, 4]] should return a padded grid. Its interior cell demonstrates why construction subtracts an overlap.
| Step | Executed statement | State | Why |
|---|---|---|---|
| Allocate boundaries | rows,cols=len(matrix),len(matrix[0]);prefix=[[0]*(cols+1) for _ in range(rows+1)] |
prefix is a 3 by 3 zero grid with independent rows |
Boundary zero in either axis describes an empty region. |
| First cell | prefix[row+1][col+1]=matrix[row][col]+prefix[row][col+1]+prefix[row+1][col]-prefix[row][col] |
prefix[1][1]=2+0+0-0=2 |
The first origin rectangle contains one value. |
| Complete first row | prefix[row+1][col+1]=matrix[row][col]+prefix[row][col+1]+prefix[row+1][col]-prefix[row][col] |
prefix[1][2]=1+0+2-0=3 |
The left origin region supplies the earlier column. |
| Start second row | prefix[row+1][col+1]=matrix[row][col]+prefix[row][col+1]+prefix[row+1][col]-prefix[row][col] |
prefix[2][1]=3+2+0-0=5 |
The upper origin region supplies the earlier row. |
| Interior overlap | prefix[row+1][col+1]=matrix[row][col]+prefix[row][col+1]+prefix[row+1][col]-prefix[row][col] |
prefix[2][2]=4+3+5-2=10 |
Both upper and left regions contain 2, so subtract that duplicate. |
| Return grid | return prefix |
[[0,0,0],[0,2,3],[0,5,10]] |
Every coordinate now owns one well-defined origin rectangle. |
| Output | |
|---|---|
print(prefix_grid([[2, 1], [3, 4]])) |
[[0, 0, 0], [0, 2, 3], [0, 5, 10]] |
A half-open query [top,left,bottom,right] starts with the origin rectangle ending at bottom/right. Subtract the strip above top and the strip left of left. Their shared upper-left corner has now been subtracted twice, so add it back. The signs reverse relative to construction because the query is removing outside regions. The query Lab returns [] for an empty matrix; use valid in-bounds queries on a nonempty rectangular matrix.
def rectangle_sums(matrix,queries):
if not matrix:return []
rows,cols=len(matrix),len(matrix[0]);prefix=[[0]*(cols+1) for _ in range(rows+1)]
for r in range(rows):
for c in range(cols):prefix[r+1][c+1]=matrix[r][c]+prefix[r][c+1]+prefix[r+1][c]-prefix[r][c]
return [prefix[b][right]-prefix[t][right]-prefix[b][left]+prefix[t][left] for t,left,b,right in queries]Implement rectangle_sums(matrix,queries). matrix is rectangular with equal row widths. Queries are valid half-open [top,left,bottom,right] bounds: 0 <= top <= bottom <= rows and 0 <= left <= right <= cols. Return each rectangle sum; empty outer input returns [].
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
def rectangle_sums(matrix,queries):
if not matrix:return []
rows,cols=len(matrix),len(matrix[0]);prefix=[[0]*(cols+1) for _ in range(rows+1)]
for r in range(rows):
for c in range(cols):prefix[r+1][c+1]=matrix[r][c]+prefix[r][c+1]+prefix[r+1][c]-prefix[r][c]
return [prefix[b][right]-prefix[t][right]-prefix[b][left]+prefix[t][left] for t,left,b,right in queries]One direct query costs its rectangle area without storing an entire prefix grid. Repeated arbitrary rectangles justify O(RC) preprocessing and O(1) per query. Per-row prefixes still use O(RC) storage if all rows are stored, but each query costs O(height); they are an implementation tradeoff, not an automatic memory reduction. A changing matrix requires rebuilding or an update-aware structure.
Name the region owned by each prefix coordinate and mark whether query endpoints are exclusive. Check one origin rectangle, one interior rectangle and an empty-height rectangle before quoting O((R+1)(C+1)+q) total time. Rectangle sum lookup is a separate operation from searching for a value in a sorted matrix; do not transfer a sum formula simply because both use a grid.
Python 3.11+
Independent Python lists are required for prefix rows; multiplying a list of one row aliases mutable rows rather than making a grid.
Verify in Python docs(opens in a new tab)Interview bounds depend on the stated representation, input model, and real Python operations.
| Operation | Average | Worst | Interview note |
|---|---|---|---|
| 2D prefix construction and q rectangle queries | O((R+1)(C+1) + q) | O((R+1)(C+1) + q) | Each rectangular input cell is visited once and each valid query reads four prefix cells. |
O((R+1)(C+1)) padded prefix storage plus O(q) returned results.
These are the mistakes most likely to survive a happy-path example and fail a boundary case.
Multiplying a list containing one row repeats references, so writing prefix[1][1] changes unrelated boundary rows too.
Prevent it: Allocate each row with a comprehension so updates cannot leak between rows.
prefix = [[0]*3]*3
prefix[1][1]=5prefix = [[0]*3 for _ in range(3)]
prefix[1][1]=5Where you will hit this: Answer Matrix Region Sums(opens in a new tab)
For the lower-right cell, subtracting top and left strips without adding their overlap yields 2 instead of 4.
Prevent it: Restore prefix[top][left] after subtracting the two outside strips.
total = prefix[bottom][right]-prefix[top][right]-prefix[bottom][left]total = prefix[bottom][right]-prefix[top][right]-prefix[bottom][left]+prefix[top][left]Where you will hit this: Answer Matrix Region Sums(opens in a new tab)
For [0,0,1,1], the exclusive lower/right corner already encloses only the first cell; adding one includes the whole 2 by 2 matrix.
Prevent it: Use the supplied half-open bottom and right directly; convert inclusive external inputs once at the boundary.
total = prefix[bottom+1][right+1]total = prefix[bottom][right]Where you will hit this: Binary Subarrays With Sum(opens in a new tab)
Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.
python-docs · checked 2026-07-27
leetcode · checked 2026-07-12