Skip to contentKEEP THE CRAFTTHE SANCTUARY

2D Prefix Sum

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…

2D Prefix Sum Code Labs

Extend Boundaries to a Grid

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.

Subtract the Overlap While Building

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.

Build a Padded 2D Prefix Grid

Reference
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 prefix
Practice

Implement 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]].

Public tests

  • Use inclusion exclusion while building

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Build a Padded 2D Prefix Grid

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 prefix

Build an Interior Cell without Double Counting

The 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.
Print Output
print(prefix_grid([[2, 1], [3, 4]])) [[0, 0, 0], [0, 2, 3], [0, 5, 10]]

Restore the Overlap While Querying

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.

Answer Rectangle Sum Queries

Reference
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]
Practice

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 [].

Public tests

  • Cancel outside strips and restore overlap

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Answer Rectangle Sum Queries

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]

Decide Whether Full Preprocessing Is Worth It

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.

Explain the Four Corners in an Interview

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 Version Note

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
2D prefix construction and q rectangle queriesO((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.

Space

O((R+1)(C+1)) padded prefix storage plus O(q) returned results.

Assumptions

  • Matrix rows have equal length. Query top/bottom and left/right are valid half-open boundaries; values are not changed after preprocessing.
  • Independent Python lists are required for prefix rows; multiplying a list of one row aliases mutable rows rather than making a grid.
  • O(RC) shorthand assumes positive row and column counts; zero-width rows still allocate one padded column.

Invariants Worth Saying Aloud

  1. prefix[r][c] contains exactly original rows before r and columns before c.
  2. Construction subtracts the overlap counted by top and left; a query adds back the overlap subtracted by its two outside strips.

When To Use Or Avoid 2D Prefix Sum

Use It When

  • Preprocess a rectangular matrix for repeated valid half-open rectangle queries.
  • Use padded zero row and column so edge rectangles need no negative-index branches.

Choose Another Tool When

  • Use a direct rectangle scan when only one small region is needed.
  • Use update-aware structures when matrix values change; simple row-prefix tables trade O(height) queries rather than asymptotically less total storage.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Aliasing all prefix rows

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.

Avoid

prefix = [[0]*3]*3
prefix[1][1]=5

Use instead

prefix = [[0]*3 for _ in range(3)]
prefix[1][1]=5

Subtracting the query overlap twice

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.

Avoid

total = prefix[bottom][right]-prefix[top][right]-prefix[bottom][left]

Use instead

total = prefix[bottom][right]-prefix[top][right]-prefix[bottom][left]+prefix[top][left]

Treating exclusive corners as inclusive

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.

Avoid

total = prefix[bottom+1][right+1]

Use instead

total = prefix[bottom][right]

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.