Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

The Largest Rectangle & Maximal Submatrices

From histograms to the biggest all-ones rectangle in a binary matrix.

Draw nn bars and ask for the largest rectangle that fits under them. There are n(n+1)/2n(n+1)/2 contiguous runs of bars to try, yet a single left-to-right pass with a stack finds the answer, and run once per row it finds the largest all-ones rectangle in a binary image. Among points in the plane, the same question turns out to be far harder.

What you’ll learn

  • Prove that some optimal rectangle under a histogram is the maximal rectangle of a single bar, bounded by its nearest strictly smaller bars.
  • Prove the stack algorithm correct, ties included, using n+1n + 1 pushes and at most nn pops.
  • Find the largest all-ones rectangle in an R×CR \times C binary matrix in O(RC)O(RC) time, prove that this is optimal, and show that there are at most RCRC maximal all-ones rectangles.
  • Contrast rectangles with squares, which a three-neighbor dynamic program handles.
  • Describe the maximum empty rectangle among nn points: Θ(n2)\Theta(n^2) maximal rectangles in the worst case, O(nlog⁡n)O(n \log n) in expectation for random points, and the classic algorithms.

Every optimal rectangle rests on its lowest bar

Proof. Take an optimal rectangle over bars l..rl..r with positive area. Raising it to height min⁡h[l..r]\min h[l..r] keeps it under the histogram and cannot shrink it, so assume its height is h[m]h[m] for a lowest bar mm of the range. Every bar in l..rl..r is at least h[m]h[m] tall. If bar l−1l - 1 existed and were at least h[m]h[m] tall, widening the rectangle would increase its area, so l−1=PS(m)l - 1 = \mathrm{PS}(m); likewise r+1=NS(m)r + 1 = \mathrm{NS}(m). So the optimum is a maximal rectangle of a bar, and the problem reduces to nearest smaller values.

Two slower routes are worth knowing. Fixing ll and extending rr with a running minimum checks all n(n+1)/2n(n+1)/2 runs in O(n2)O(n^2). Divide and conquer at the lowest bar, OPT(l,r)=max⁡{h[m](r−l+1), OPT(l,m−1), OPT(m+1,r)}\mathrm{OPT}(l, r) = \max\{h[m](r - l + 1),\ \mathrm{OPT}(l, m - 1),\ \mathrm{OPT}(m + 1, r)\}, takes Θ(n2)\Theta(n^2) on sorted heights if the minimum is found by scanning, but O(n)O(n) after preprocessing if a range minimum query finds it in O(1)O(1). Its recursion tree is the Cartesian tree of the heights, the subject of the next Optimal lesson.

Check your understanding

For the heights [2,4,4,1,3,5,4,2][2, 4, 4, 1, 3, 5, 4, 2], what is the area of the maximal rectangle of the bar of height 3, at index 4?

  1. 3
  2. 9
  3. 12
  4. 15
Show the answer

B. 9

The previous strictly lower bar is the 1 at index 3, and the next is the 2 at index 7, so the rectangle covers bars 4 to 6 (heights 3, 5 and 4): width 3, area 9. It is also the largest rectangle under these bars.

The one-pass stack algorithm, ties included

python
def largest_rectangle(h):
    best, stack = 0, []                 # indices; heights strictly increase upward
    for i, x in enumerate(h + [0]):     # a final bar of height 0 flushes the stack
        while stack and h[stack[-1]] >= x:
            m = stack.pop()
            left = stack[-1] if stack else -1
            best = max(best, h[m] * (i - left - 1))
        stack.append(i)
    return best

The stack holds indices whose heights strictly increase from bottom to top. When bar mm is popped by bar ii, the index below it on the stack, left, bounds its rectangle on the left and ii bounds it on the right.

DerivationProof
  1. h[s1]<h[s2]<⋯<h[stop]h[s_1] < h[s_2] < \cdots < h[s_{\text{top}}]

    Heights on the stack strictly increase, because before ii is pushed every index with height ≥h[i]\ge h[i] is popped. In particular, whenever yy pops xx, h[x]≥h[y]h[x] \ge h[y].

  2. h[m] (i−ℓ−1) ≤ OPTh[m]\,(i - \ell - 1) \ \le\ \mathrm{OPT}

    Every computed area fits. Let mm be popped by ii, with ℓ\ell just below it. Each bar strictly between ℓ\ell and mm left the stack through a chain of pops ending at mm, so it is at least h[m]h[m] tall. Each bar strictly between mm and ii sat above mm on the stack, or was popped by one that did, so it is taller than h[m]h[m]. Hence bars ℓ+1..i−1\ell + 1..i - 1 are all at least h[m]h[m] tall:

  3. area computed when m⋆ is popped  =  t (N−P−1)\text{area computed when } m^\star \text{ is popped} \;=\; t\,(N - P - 1)

    Every maximal rectangle is found. Take a maximal rectangle (P,N)(P, N) of height tt, and let m⋆m^\star be the rightmost bar of height tt inside it. Bars strictly between m⋆m^\star and NN are taller than tt, so the first bar that can pop m⋆m^\star is NN (or the sentinel). Bars strictly between PP and m⋆m^\star are at least tt tall, so none is left on the stack when m⋆m^\star is pushed, while PP, lower than all of them, is never popped by them: PP lies directly below m⋆m^\star.

  4. max⁡pops h[m] (i−ℓ−1)  =  OPT\max_{\text{pops}}\ h[m]\,(i - \ell - 1) \;=\; \mathrm{OPT}

    Conclusion. No computed area exceeds OPT\mathrm{OPT}, and the maximal rectangle that attains OPT\mathrm{OPT} is computed. Each index is pushed once and popped at most once, and the sentinel is never popped.

All-ones rectangles in a binary matrix

In an R×CR \times C matrix of 0s and 1s, find the largest rectangle of 1s. For each row rr, let heights[c]\text{heights}[c] count the consecutive 1s in column cc that end at row rr: it resets to 0 at a 0 and grows by one at a 1. Every all-ones rectangle has a bottom row, and with that row's heights it is a rectangle under the histogram; conversely, every rectangle under that histogram is all ones. So one histogram per row solves the problem.

python
def largest_ones_rectangle(grid):
    best, heights = 0, [0] * len(grid[0])
    for row in grid:
        for c, cell in enumerate(row):
            heights[c] = heights[c] + 1 if cell else 0
        best = max(best, largest_rectangle(heights))
    return best

O(RC)O(RC) time and O(C)O(C) extra space, which is optimal: on the all-ones matrix (answer RCRC), an algorithm that never reads some cell cannot tell it apart from the same matrix with that cell set to 0, whose answer is smaller. So every algorithm must read all RCRC cells in the worst case.

Row of the matrixHeights after this rowLargest rectangle with this bottom row
1 1 1 1 1 11,1,1,1,1,11, 1, 1, 1, 1, 16
1 1 1 1 1 12,2,2,2,2,22, 2, 2, 2, 2, 212
1 0 1 1 0 13,0,3,3,0,33, 0, 3, 3, 0, 36
1 1 1 0 1 14,1,4,0,1,44, 1, 4, 0, 1, 44
A worked example: the largest all-ones rectangle is the 2×62 \times 6 block formed by the first two rows, area 12.

Squares are easier. Let s[i][j]s[i][j] be the side of the largest all-ones square whose bottom-right corner is cell (i,j)(i, j). Then s[i][j]=0s[i][j] = 0 at a 0, and otherwise

s[i][j]=1+min⁡(s[i−1][j], s[i][j−1], s[i−1][j−1]),s[i][j] = 1 + \min\big(s[i-1][j],\ s[i][j-1],\ s[i-1][j-1]\big),

an O(RC)O(RC) dynamic program: a square of side kk ends at (i,j)(i, j) exactly when squares of side k−1k - 1 end at the three neighbors. Rectangles have no such recurrence, because the best rectangle ending at a cell is not a single number: a tall thin one and a short wide one may both be maximal, and either may grow into the eventual optimum. The histogram method sidesteps this by fixing the bottom row.

Predict before you look

In the matrix of the table above, what is the side of the largest all-ones square?

Show the answer

2

Any 3×33 \times 3 square spans three consecutive rows, so it includes the third row, 1 0 1 1 0 1, whose longest run of 1s has length 2. The largest square therefore has side 2 and area 4, while the largest rectangle has area 12.

Among points: the maximum empty rectangle

This is the continuous cousin of the matrix problem, with points in place of zeros, and the difficulty is the number of candidates. Naamad, Lee and Hsu (1984) proved that there are O(n2)O(n^2) maximal empty rectangles, gave configurations with quadratically many, and found the largest in O(min⁡(n2,slog⁡n))O(\min(n^2, s \log n)) time, where ss is the number of maximal empty rectangles; for points placed uniformly at random, ss is only O(nlog⁡n)O(n \log n) in expectation.

Counting them confirms both regimes. Two staircases of kk points each, one rising in the upper left of the box and one rising in the lower right, produce exactly k2+8k−1k^2 + 8k - 1 maximal empty rectangles: one for every pair of points taken from the two staircases, plus a few more. A simulation with 2,000 uniformly random points finds about 30,800 on average, close to 2nln⁡n≈30,4002n \ln n \approx 30{,}400.

The largest empty rectangle can be found without listing every maximal one. Chazelle, Drysdale and Lee (1986) gave an O(nlog⁡3n)O(n \log^3 n) algorithm, and Aggarwal and Suri (1987) improved it to O(nlog⁡2n)O(n \log^2 n). On a grid, the problem is exactly the all-ones rectangle of the previous step, solved in time linear in the number of cells.

Key takeaways

  • Some optimal rectangle under a histogram is the maximal rectangle of one bar, bounded by its previous and next strictly smaller bars.
  • The stack algorithm computes only rectangles that fit, and the rightmost bar of each height computes its full maximal rectangle, so it is exact, ties included, with n+1n + 1 pushes and at most nn pops.
  • Row-by-row heights reduce the largest all-ones rectangle in an R×CR \times C matrix to RR histograms: O(RC)O(RC) time, which is optimal, and at most RCRC maximal rectangles. Squares have a simpler three-neighbor dynamic program.
  • Among nn points, maximal empty rectangles number Θ(n2)\Theta(n^2) in the worst case but O(nlog⁡n)O(n \log n) in expectation for random points, and the largest can be found in O(nlog⁡2n)O(n \log^2 n) time (Aggarwal & Suri, 1987).

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

When a bar of equal height arrives, the stack algorithm pops bar mm and computes a rectangle for it that is too narrow. Why is the final answer still correct?

  1. It is not: equal heights need a second pass
  2. The narrow rectangle still fits under the histogram, and the rightmost bar of that height later computes the full maximal rectangle
  3. Histograms cannot contain equal heights
  4. Popping on equality makes the stack non-decreasing, so nothing is lost
Show the answer

B. The narrow rectangle still fits under the histogram, and the rightmost bar of that height later computes the full maximal rectangle

Every computed area belongs to a rectangle that fits, so none exceeds the optimum. For each maximal rectangle, the rightmost bar of its height is popped exactly by the next strictly lower bar, with the previous strictly lower bar directly beneath it, so it computes the full rectangle.

Question 2

Why does running the histogram algorithm on every row find the largest all-ones rectangle of a binary matrix?

  1. Every all-ones rectangle has a bottom row, and with that row's column heights it is a rectangle under the histogram
  2. The largest rectangle always touches the last row
  3. Each column's height is the number of 1s in the whole column
  4. It finds the largest square, and the largest rectangle is always a square
Show the answer

A. Every all-ones rectangle has a bottom row, and with that row's column heights it is a rectangle under the histogram

With heights counting the consecutive 1s that end at row rr, the rectangles under row rr's histogram are exactly the all-ones rectangles whose bottom row is rr. Taking the best over all rows covers every rectangle, in O(RC)O(RC) time in total.

Question 3

How many maximal empty rectangles can nn points in a box have?

  1. At most nn
  2. O(nlog⁡n)O(n \log n) in the worst case
  3. Θ(n2)\Theta(n^2) in the worst case, but O(nlog⁡n)O(n \log n) in expectation for uniformly random points
  4. Exponentially many
Show the answer

C. Θ(n2)\Theta(n^2) in the worst case, but O(nlog⁡n)O(n \log n) in expectation for uniformly random points

Naamad, Lee and Hsu (1984) proved the O(n2)O(n^2) upper bound and gave quadratic examples, such as two staircases of points; for random points the expected number is O(nlog⁡n)O(n \log n). That is why their O(min⁡(n2,slog⁡n))O(\min(n^2, s \log n)) algorithm is fast on typical inputs.

Question 4

Why does every algorithm for the largest all-ones rectangle in an R×CR \times C matrix need Ω(RC)\Omega(RC) time in the worst case?

  1. Because the cells must first be sorted
  2. Because the number of rectangles is Θ(R2C2)\Theta(R^2C^2)
  3. It does not: O(R+C)O(R + C) suffices with prefix sums
  4. Because on the all-ones matrix any unread cell could be a 0, which would change the answer
Show the answer

D. Because on the all-ones matrix any unread cell could be a 0, which would change the answer

An adversary argument: if an algorithm finishes on the all-ones matrix without reading some cell, it answers RCRC; flipping that unread cell to 0 gives a matrix with a smaller answer, on which the algorithm behaves identically. So it must read every cell.

Further reading

  • A. Naamad, D. T. Lee & W.-L. Hsu, "On the maximum empty rectangle problem," Discrete Applied Mathematics 8 (1984).
  • B. Chazelle, R. L. Drysdale & D. T. Lee, "Computing the largest empty rectangle," SIAM Journal on Computing 15 (1986).
  • A. Aggarwal & S. Suri, "Fast algorithms for computing the largest empty rectangle," Proceedings of the 3rd ACM Symposium on Computational Geometry (1987).
  • A. Laaksonen, Competitive Programmer's Handbook (2018, free online), chapter 8.