Prefix sums on a grid
🌍 In real life. A mango orchard in Rajshahi is split into plots in rows and columns, and the owner knows how many trees each plot has. Buyers keep asking: "how many trees in the plots from row 1 to 2 and column 1 to 3?" Counting plot by plot for every question is slow when the orchard is big. Instead, the owner writes once, for every plot, the total of all plots above and to the left of it. Then any rectangle is a sum of four of those numbers.
The idea in one sentence: P[r][c] is the sum of the top-left block grid[0:r] × [0:c], with an extra row and column of zeros, and any rectangle's sum comes from four entries of P.
Its words:
- 2D prefix sum:
P[r][c], the sum of the block above and to the left of row r, column c - padding: the extra row and column of zeros, so the first row and column need no special case
- inclusion–exclusion: add two blocks that overlap, then take the overlap away once
How it works, step by step:
- make P with one more row and one more column than the grid, all 0
- fill it row by row, left to right (the same order as the loop below walks the grid):
P[r + 1][c + 1] = grid[r][c] + P[r][c + 1] + P[r + 1][c] - P[r][c] - the rectangle with rows r1..r2 and columns c1..c2 (both ends included) adds up to
P[r2 + 1][c2 + 1] - P[r1][c2 + 1] - P[r2 + 1][c1] + P[r1][c1]
Watch the order a row-by-row loop visits the plots; P is filled in exactly this order, each entry using the ones above and to its left:
Why it is correct (inclusion and exclusion). To build P[r + 1][c + 1], add the block above (P[r][c + 1]) and the block to the left (P[r + 1][c]): their overlap, the top-left corner P[r][c], was added twice, so subtract it once, then add the plot itself. A rectangle works the same way backwards: take the big top-left block, take away the strip above it and the strip to its left, and add back their overlap, which was taken away twice.
What it costs, worked out. Building P visits each of the R × C plots once: O(R × C). Each rectangle is then 4 lookups and 3 additions or subtractions: O(1), instead of adding up every plot in it. For a 1,000 × 1,000 orchard and 10,000 questions about big rectangles, that is about 1 million steps to build plus 70,000, against up to 10 billion.
grid = [[3, 1, 4],
[1, 5, 9],
[2, 6, 5]]
rows, cols = len(grid), len(grid[0])
P = [[0] * (cols + 1) for _ in range(rows + 1)]
for r in range(rows):
for c in range(cols):
P[r + 1][c + 1] = grid[r][c] + P[r][c + 1] + P[r + 1][c] - P[r][c]
for row in P:
print(row)
def rect_sum(P, r1, c1, r2, c2): # rows r1..r2, columns c1..c2, ends included
return P[r2 + 1][c2 + 1] - P[r1][c2 + 1] - P[r2 + 1][c1] + P[r1][c1]
print(rect_sum(P, 1, 1, 2, 2)) # 5 + 9 + 6 + 5Mistakes and edge cases.
- forgetting
- P[r][c]counts the corner twice, and the error grows with every entry - in the rectangle formula, adding back
P[r1][c1]is easy to forget: it was subtracted twice - mixing "ends included" with slice-style ends: with included ends it is
r2 + 1andc2 + 1 - building P with
[[0] * (cols + 1)] * (rows + 1)makes every row the same list (Chapter 34): use a comprehension
Quiz
What does this print?
grid = [[1, 2], [3, 4]] P = [[0] * 3 for _ in range(3)] for r in range(2): for c in range(2): P[r + 1][c + 1] = grid[r][c] + P[r][c + 1] + P[r + 1][c] - P[r][c] print(P[2][2], P[1][2], P[2][1])Why does building P subtract P[r][c]?
- The block above and the block to the left both contain the top-left corner, so it was added twice
- To keep the numbers small
- Because grid[r][c] is counted in it
With P for [[1, 2], [3, 4]] (P[2][2] = 10, P[1][2] = 3, P[2][1] = 4, P[1][1] = 1), what is the sum of just the bottom-right plot? What does this print?
print(10 - 3 - 4 + 1)An R × C grid and q rectangle questions. What does the grid prefix sum cost?
- O(R × C + q)
- O(R × C × q)
- O(q)
The whole grid adds up to 36, but P[3][3] comes out as 60. Which line is wrong?
grid = [[3, 1, 4], [1, 5, 9], [2, 6, 5]] rows, cols = len(grid), len(grid[0]) P = [[0] * (cols + 1) for _ in range(rows + 1)] for r in range(rows): for c in range(cols): P[r + 1][c + 1] = grid[r][c] + P[r][c + 1] + P[r + 1][c] print(P[rows][cols])
Coding tasks
Write
grid_prefix(grid): the table P with one more row and column thangrid, whereP[r][c]is the sum ofgridrows 0..r − 1 and columns 0..c − 1 (so row 0 and column 0 are all zeros).Write
rect_sums(grid, rects): build the grid prefix sum once, then for each rectangle (r1, c1, r2, c2) inrects(rows r1..r2 and columns c1..c2, ends included) give its sum, as a list.