Skip to lesson

How do you sum any rectangular region (r1, c1) to (r2, c2) of an R × C matrix in O(1) time? By extending the 1D padded prefix sum array into a (R + 1) × (C + 1) table and applying the principle of inclusion-exclusion.

Sum of a sub-rectangle and Inclusion and exclusion

A padded 2D table pref stores in each cell the sum of the rectangle from the top-left corner up to that cell.

  1. Allocate long[][] pref = new long[R + 1][C + 1] (row 0 and col 0 are zeroes).
  2. Build: pref[r + 1][c + 1] = pref[r][c + 1] + pref[r + 1][c] - pref[r][c] + mat[r][c].
  3. Query [r1..r2][c1..c2]: pref[r2 + 1][c2 + 1] - pref[r1][c2 + 1] - pref[r2 + 1][c1] + pref[r1][c1].

Example 1 · Range Sum Query 2D (Immutable)

NumMatrixDemo.javaJava
public class NumMatrixDemo {    static class NumMatrix {        private final long[][] pref;
        NumMatrix(int[][] matrix) {            int R = matrix.length;            int C = matrix[0].length;            this.pref = new long[R + 1][C + 1];            for (int r = 0; r < R; r++) {                for (int c = 0; c < C; c++) {                    pref[r + 1][c + 1] = pref[r][c + 1] + pref[r + 1][c]                            - pref[r][c] + matrix[r][c];                }            }        }
        public long sumRegion(int r1, int c1, int r2, int c2) {            return pref[r2 + 1][c2 + 1]                    - pref[r1][c2 + 1]                    - pref[r2 + 1][c1]                    + pref[r1][c1];        }    }
    public static void main(String[] args) {        int[][] mat = {            {3, 0, 1, 4, 2},            {5, 6, 3, 2, 1},            {1, 2, 0, 1, 5},            {4, 1, 0, 1, 7},            {1, 0, 3, 0, 5}        };        NumMatrix nm = new NumMatrix(mat);        System.out.println("sumRegion(2, 1, 4, 3): " + nm.sumRegion(2, 1, 4, 3));        System.out.println("sumRegion(1, 1, 2, 2): " + nm.sumRegion(1, 1, 2, 2));        System.out.println("sumRegion(1, 2, 2, 4): " + nm.sumRegion(1, 2, 2, 4));    }}
Output
sumRegion(2, 1, 4, 3): 8
sumRegion(1, 1, 2, 2): 11
sumRegion(1, 2, 2, 4): 12

What this code does

  • Building the 6x6 padded pref table takes O(R * C) time once.
  • Each sumRegion call performs 4 array lookups and 3 arithmetic operations in O(1) time.

Example 2 · Largest 1-filled square in a binary matrix using 2D prefix sums

MaximalSquarePrefixDemo.javaJava
public class MaximalSquarePrefixDemo {    public static int maxSquareSide(int[][] grid) {        int R = grid.length, C = grid[0].length;        int[][] pref = new int[R + 1][C + 1];        for (int r = 0; r < R; r++) {            for (int c = 0; c < C; c++) {                pref[r + 1][c + 1] = pref[r][c + 1] + pref[r + 1][c] - pref[r][c] + grid[r][c];            }        }        int bestSide = 0;        for (int r = 0; r < R; r++) {            for (int c = 0; c < C; c++) {                for (int s = bestSide + 1; r + s <= R && c + s <= C; s++) {                    int r2 = r + s - 1, c2 = c + s - 1;                    int sum = pref[r2 + 1][c2 + 1] - pref[r][c2 + 1] - pref[r2 + 1][c] + pref[r][c];                    if (sum == s * s) {                        bestSide = s;                    } else {                        break;                    }                }            }        }        return bestSide;    }
    public static void main(String[] args) {        int[][] grid = {            {1, 0, 1, 0, 0},            {1, 0, 1, 1, 1},            {1, 1, 1, 1, 1},            {1, 0, 0, 1, 0}        };        int side = maxSquareSide(grid);        System.out.println("Max square side: " + side + ", area: " + (side * side));    }}
Output
Max square side: 2, area: 4

What this code does

  • An s x s subgrid of a binary matrix contains all 1s if and only if its 2D range sum equals s * s.
  • With O(1) 2D range sum queries, checking whether any s x s square is all 1s takes O(1) time.

Given an R × C matrix mat, we allocate a padded 2D array long[][] pref = new long[R + 1][C + 1] where row 0 and column 0 are all zeroes, and pref[r + 1][c + 1] stores the sum of the origin-anchored rectangle mat[0 .. r][0 .. c].

Building pref[r + 1][c + 1] in O(1) per cell: To compute the rectangle from (0, 0) to (r, c), we add the rectangle above (pref[r][c + 1]), add the rectangle to the left (pref[r + 1][c]), subtract their top-left overlap (pref[r][c], which was counted in both!), and add the new corner cell mat[r][c]: pref[r + 1][c + 1] = pref[r][c + 1] + pref[r + 1][c] - pref[r][c] + mat[r][c] Querying sumRegion(r1, c1, r2, c2) in O(1): To isolate the sub-rectangle mat[r1 .. r2][c1 .. c2], start with the big rectangle pref[r2 + 1][c2 + 1], subtract the strip above row r1 (pref[r1][c2 + 1]), subtract the strip left of column c1 (pref[r2 + 1][c1]), and add back the top-left corner pref[r1][c1] because it was subtracted twice: sumRegion(r₁, c₁, r₂, c₂) = pref[r₂ + 1][c₂ + 1] - pref[r₁][c₂ + 1] - pref[r₂ + 1][c₁] + pref[r₁][c₁]

Notice the sign symmetry: when BUILDING, you add two neighbors and SUBTRACT the top-left overlap (- pref[r][c]); when QUERYING, you subtract two strips and ADD BACK the top-left overlap (+ pref[r1][c1]).

Real world: summing regions of an image

In computer vision and image processing, a 2D prefix sum table is known as an integral image (or summed-area table, popularized by the Viola–Jones face detection algorithm in 2001).

Example 3 · Image Box Blur / Matrix Block Sum

MatrixBlockSumDemo.javaJava
import java.util.Arrays;
public class MatrixBlockSumDemo {    public static int[][] matrixBlockSum(int[][] mat, int k) {        int R = mat.length, C = mat[0].length;        int[][] pref = new int[R + 1][C + 1];        for (int r = 0; r < R; r++) {            for (int c = 0; c < C; c++) {                pref[r + 1][c + 1] = pref[r][c + 1] + pref[r + 1][c] - pref[r][c] + mat[r][c];            }        }        int[][] ans = new int[R][C];        for (int r = 0; r < R; r++) {            for (int c = 0; c < C; c++) {                int r1 = Math.max(0, r - k), c1 = Math.max(0, c - k);                int r2 = Math.min(R - 1, r + k), c2 = Math.min(C - 1, c + k);                ans[r][c] = pref[r2 + 1][c2 + 1] - pref[r1][c2 + 1]                        - pref[r2 + 1][c1] + pref[r1][c1];            }        }        return ans;    }
    public static void main(String[] args) {        int[][] mat = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};        int[][] blurred = matrixBlockSum(mat, 1);        for (int[] row : blurred) {            System.out.println(Arrays.toString(row));        }    }}
Output
[12, 21, 16]
[27, 45, 33]
[24, 39, 28]

What this code does

  • For center cell (1, 1) with k = 1, the clamped region is [0..2][0..2], summing all 9 cells to 45.
  • For corner cell (0, 0) with k = 1, the clamped region is [0..1][0..1], summing 1 + 2 + 4 + 5 = 12.
  • Clamp neighborhood bounds to the matrix: r1 = Math.max(0, r - k), c1 = Math.max(0, c - k), r2 = Math.min(R - 1, r + k), c2 = Math.min(C - 1, c + k).
  • Cost of box blur over R x C pixels with radius k: O(R * C) total time, completely independent of k.

Why does every graphics and vision library use integral images?

  • Box blur (Matrix Block Sum): Blurring an image replaces each pixel (r, c) with the average of its (2k + 1) × (2k + 1) neighborhood [r - k .. r + k][c - k .. c + k] (clamped to image bounds). Without a 2D prefix sum, a box blur with radius k = 25 does 51 × 51 = 2,601 additions per pixel. With a 2D prefix sum, every blur radius k costs just 4 table lookups (O(1)) per pixel!

Next step

Check your understanding

10 quick questions