2D prefix sum
Intermediate · 9 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
A 2D prefix sum stores, for every cell of a grid, the total of the rectangle from the top-left corner to that cell. Then the total of any rectangle comes from four stored values with a little add and subtract, no matter how big the rectangle is.
Practical use cases
- Web app: Sales in a selected map region. A heat-map page lets a manager drag a box over a map of cities to see total orders inside it. Pre-computing rectangle totals means the number updates live while dragging, rather than adding up thousands of cells per mouse move.
- Web app: Spreadsheet-style analytics grid. An online report with rows as products and columns as months lets the user select any block and see its sum. Four lookups give the answer, so selecting a huge block is as quick as a small one. Even a spreadsheet of a million cells responds immediately, because the work never depends on how big the selected block is.
- System: Image processing and game engines. Blur filters and face detectors use "integral images" to sum pixel blocks instantly, and game engines total resources across map regions the same way. Each box sum takes just four lookups, so thousands of boxes can be summed every second.
The story: The Mango Orchard Map
Grandpa Bhaskar has a small orchard behind the house: mango trees planted in neat rows and columns, like a chessboard. Every summer he counts the mangoes on each tree and draws a big grid with the numbers.
Then the buyers arrive. "How many mangoes in the north-east corner?" "And in that patch near the well?" "And the middle block?" Each buyer points at a rectangle of trees, and each time Grandpa counts every tree inside it. With a few trees it is fine. When Aarav's father showed him a huge farm of ten thousand trees, counting rectangle after rectangle became impossible.
Mira remembered the passbook trick. "One line of numbers needs a running total. A grid of numbers needs a running total over a rectangle." She drew a second grid where every box holds the total of everything above and to its left. To answer a question, you take the big block, cut off the strip above, cut off the strip on the left, and put back the little corner you cut twice. Four lookups, any rectangle. They called it the 2D prefix sum.
How to spot this problem, and where you need it
You have a grid of numbers and are asked again and again for the total inside different rectangles, and adding up every cell in each rectangle is slow.
Signs you need it
- The data is a table or grid (rows by columns, a map, an image) and queries pick rectangular blocks.
- A double for-loop adds cells inside the selected rectangle on each query.
- The user drags or resizes a selection and the page lags.
- The problem says "sum of a submatrix" with many queries.
Where to use it in a project
- Map and heat-map dashboards where users select a region.
- Analytics tables where users select a block of rows and months to total.
- Image-processing helpers that need quick sums over small pixel boxes.
The solution
Make a second grid where each cell holds the sum of the rectangle from the top-left corner down to that cell, built in one pass. To total any rectangle, take the big corner value, subtract the strip above it and the strip to its left, and add back the piece you subtracted twice. That is four lookups for any rectangle size.
Payoff: Before: adding up to a million cells per selection. After: four lookups, so dragging a selection stays smooth.
Explain it like I am 8
Think of a chocolate bar with raisins in some squares. For every square, write how many raisins are in the piece from the top-left corner up to that square. To count raisins in any rectangle later: take the big piece, cut away the top strip, cut away the left strip, and add back the corner you cut away twice.
How it works, step by step
- Add a border of zeros on the top and left of a new grid of the same shape plus one.
- Fill each box:
own + above + left - corner-above-left. The corner is subtracted because above and left both include it. - Ask a rectangle from (r1, c1) to (r2, c2) with four lookups in the new grid.
- Combine: big block
- strip above - strip left + corner. - Cost: building touches every box once, and every later question takes just four lookups.
The code in four languages
PHP
<?php
// P has one extra row and column of zeros. P[i][j] = sum of the first i rows and first j columns.
function buildPrefix2D(array $g): array {
$R = count($g);
$C = count($g[0]);
$P = array_fill(0, $R + 1, array_fill(0, $C + 1, 0));
for ($i = 1; $i <= $R; $i++) {
for ($j = 1; $j <= $C; $j++) {
// own + above + left - the corner counted twice
$P[$i][$j] = $g[$i - 1][$j - 1] + $P[$i - 1][$j] + $P[$i][$j - 1] - $P[$i - 1][$j - 1];
}
}
return $P;
}
// Rectangle from (r1,c1) to (r2,c2), all 0-based and inclusive
function rectSum(array $P, int $r1, int $c1, int $r2, int $c2): int {
return $P[$r2 + 1][$c2 + 1] // big block
- $P[$r1][$c2 + 1] // strip above
- $P[$r2 + 1][$c1] // strip on the left
+ $P[$r1][$c1]; // corner removed twice, add it back
}
$orchard = [
[3, 1, 2, 4],
[1, 5, 1, 2],
[2, 2, 6, 1],
[4, 1, 3, 2],
];
$P = buildPrefix2D($orchard);
echo rectSum($P, 1, 1, 2, 3) . PHP_EOL; // 5+1+2+2+6+1 = 17
echo rectSum($P, 0, 0, 3, 3) . PHP_EOL; // whole orchard = 40JavaScript
// P has one extra row and column of zeros. P[i][j] = sum of the first i rows and first j columns.
function buildPrefix2D(g) {
const R = g.length, C = g[0].length;
const P = Array.from({ length: R + 1 }, () => new Array(C + 1).fill(0));
for (let i = 1; i <= R; i++) {
for (let j = 1; j <= C; j++) {
// own + above + left - the corner counted twice
P[i][j] = g[i - 1][j - 1] + P[i - 1][j] + P[i][j - 1] - P[i - 1][j - 1];
}
}
return P;
}
// Rectangle from (r1,c1) to (r2,c2), all 0-based and inclusive
function rectSum(P, r1, c1, r2, c2) {
return P[r2 + 1][c2 + 1] // big block
- P[r1][c2 + 1] // strip above
- P[r2 + 1][c1] // strip on the left
+ P[r1][c1]; // corner removed twice, add it back
}
const orchard = [
[3, 1, 2, 4],
[1, 5, 1, 2],
[2, 2, 6, 1],
[4, 1, 3, 2],
];
const P = buildPrefix2D(orchard);
console.log(rectSum(P, 1, 1, 2, 3)); // 5+1+2+2+6+1 = 17
console.log(rectSum(P, 0, 0, 3, 3)); // whole orchard = 40Java
public class Main {
// P has one extra row and column of zeros. P[i][j] = sum of the first i rows and first j columns.
static int[][] buildPrefix2D(int[][] g) {
int R = g.length, C = g[0].length;
int[][] P = new int[R + 1][C + 1];
for (int i = 1; i <= R; i++) {
for (int j = 1; j <= C; j++) {
// own + above + left - the corner counted twice
P[i][j] = g[i - 1][j - 1] + P[i - 1][j] + P[i][j - 1] - P[i - 1][j - 1];
}
}
return P;
}
// Rectangle from (r1,c1) to (r2,c2), all 0-based and inclusive
static int rectSum(int[][] P, int r1, int c1, int r2, int c2) {
return P[r2 + 1][c2 + 1] // big block
- P[r1][c2 + 1] // strip above
- P[r2 + 1][c1] // strip on the left
+ P[r1][c1]; // corner removed twice, add it back
}
public static void main(String[] args) {
int[][] orchard = {
{3, 1, 2, 4},
{1, 5, 1, 2},
{2, 2, 6, 1},
{4, 1, 3, 2},
};
int[][] P = buildPrefix2D(orchard);
System.out.println(rectSum(P, 1, 1, 2, 3)); // 5+1+2+2+6+1 = 17
System.out.println(rectSum(P, 0, 0, 3, 3)); // whole orchard = 40
}
}Go
package main
import "fmt"
// buildPrefix2D: P has one extra row and column of zeros.
// P[i][j] = sum of the first i rows and first j columns.
func buildPrefix2D(g [][]int) [][]int {
R, C := len(g), len(g[0])
P := make([][]int, R+1)
for i := range P {
P[i] = make([]int, C+1)
}
for i := 1; i <= R; i++ {
for j := 1; j <= C; j++ {
// own + above + left - the corner counted twice
P[i][j] = g[i-1][j-1] + P[i-1][j] + P[i][j-1] - P[i-1][j-1]
}
}
return P
}
// rectSum: rectangle from (r1,c1) to (r2,c2), all 0-based and inclusive.
func rectSum(P [][]int, r1, c1, r2, c2 int) int {
return P[r2+1][c2+1] - // big block
P[r1][c2+1] - // strip above
P[r2+1][c1] + // strip on the left
P[r1][c1] // corner removed twice, add it back
}
func main() {
orchard := [][]int{
{3, 1, 2, 4},
{1, 5, 1, 2},
{2, 2, 6, 1},
{4, 1, 3, 2},
}
P := buildPrefix2D(orchard)
fmt.Println(rectSum(P, 1, 1, 2, 3)) // 5+1+2+2+6+1 = 17
fmt.Println(rectSum(P, 0, 0, 3, 3)) // whole orchard = 40
}Time: Build O(rows x cols), each query O(1) · Extra space: O(rows x cols). Every box is filled once, and after that any rectangle costs exactly four lookups.
Watch out for
- Forgetting to add the corner back, so the answer comes out too small by one corner patch.
- Skipping the zero border, which forces messy special cases for rectangles touching the top or left edge.
- Mixing row and column order in the four lookups. Draw the rectangle first, then name its four corners.
Quick check
- Why do we add the corner patch back at the end?
- It was never counted at all
- To make the answer even
- It was subtracted twice, once with each strip
- How many lookups answer one rectangle once the grid is built?
- As many as trees in the rectangle
- Two
- Four
- When filling a box, what do you subtract?
- The box to the right
- The box itself
- The corner above-left, counted by both above and left