The Largest Rectangle & Maximal Submatrices
From histograms to the biggest all-ones rectangle in a binary matrix.
Draw bars and ask for the largest rectangle that fits under them. There are 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 pushes and at most pops.
- Find the largest all-ones rectangle in an binary matrix in time, prove that this is optimal, and show that there are at most maximal all-ones rectangles.
- Contrast rectangles with squares, which a three-neighbor dynamic program handles.
- Describe the maximum empty rectangle among points: maximal rectangles in the worst case, in expectation for random points, and the classic algorithms.
Every optimal rectangle rests on its lowest bar
Proof. Take an optimal rectangle over bars with positive area. Raising it to height keeps it under the histogram and cannot shrink it, so assume its height is for a lowest bar of the range. Every bar in is at least tall. If bar existed and were at least tall, widening the rectangle would increase its area, so ; likewise . 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 and extending with a running minimum checks all runs in . Divide and conquer at the lowest bar, , takes on sorted heights if the minimum is found by scanning, but after preprocessing if a range minimum query finds it in . Its recursion tree is the Cartesian tree of the heights, the subject of the next Optimal lesson.
For the heights , what is the area of the maximal rectangle of the bar of height 3, at index 4?
- 3
- 9
- 12
- 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
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 bestThe stack holds indices whose heights strictly increase from bottom to top. When bar is popped by bar , the index below it on the stack, left, bounds its rectangle on the left and bounds it on the right.
Heights on the stack strictly increase, because before is pushed every index with height is popped. In particular, whenever pops , .
Every computed area fits. Let be popped by , with just below it. Each bar strictly between and left the stack through a chain of pops ending at , so it is at least tall. Each bar strictly between and sat above on the stack, or was popped by one that did, so it is taller than . Hence bars are all at least tall:
Every maximal rectangle is found. Take a maximal rectangle of height , and let be the rightmost bar of height inside it. Bars strictly between and are taller than , so the first bar that can pop is (or the sentinel). Bars strictly between and are at least tall, so none is left on the stack when is pushed, while , lower than all of them, is never popped by them: lies directly below .
Conclusion. No computed area exceeds , and the maximal rectangle that attains 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 matrix of 0s and 1s, find the largest rectangle of 1s. For each row , let count the consecutive 1s in column that end at row : 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.
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 besttime and extra space, which is optimal: on the all-ones matrix (answer ), 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 cells in the worst case.
| Row of the matrix | Heights after this row | Largest rectangle with this bottom row |
|---|---|---|
1 1 1 1 1 1 | 6 | |
1 1 1 1 1 1 | 12 | |
1 0 1 1 0 1 | 6 | |
1 1 1 0 1 1 | 4 |
Squares are easier. Let be the side of the largest all-ones square whose bottom-right corner is cell . Then at a 0, and otherwise
an dynamic program: a square of side ends at exactly when squares of side 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.
In the matrix of the table above, what is the side of the largest all-ones square?
Show the answer
2
Any 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 maximal empty rectangles, gave configurations with quadratically many, and found the largest in time, where is the number of maximal empty rectangles; for points placed uniformly at random, is only in expectation.
Counting them confirms both regimes. Two staircases of points each, one rising in the upper left of the box and one rising in the lower right, produce exactly 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 .
The largest empty rectangle can be found without listing every maximal one. Chazelle, Drysdale and Lee (1986) gave an algorithm, and Aggarwal and Suri (1987) improved it to . 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 pushes and at most pops.
- Row-by-row heights reduce the largest all-ones rectangle in an matrix to histograms: time, which is optimal, and at most maximal rectangles. Squares have a simpler three-neighbor dynamic program.
- Among points, maximal empty rectangles number in the worst case but in expectation for random points, and the largest can be found in time (Aggarwal & Suri, 1987).
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
When a bar of equal height arrives, the stack algorithm pops bar and computes a rectangle for it that is too narrow. Why is the final answer still correct?
- It is not: equal heights need a second pass
- The narrow rectangle still fits under the histogram, and the rightmost bar of that height later computes the full maximal rectangle
- Histograms cannot contain equal heights
- 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.
Why does running the histogram algorithm on every row find the largest all-ones rectangle of a binary matrix?
- Every all-ones rectangle has a bottom row, and with that row's column heights it is a rectangle under the histogram
- The largest rectangle always touches the last row
- Each column's height is the number of 1s in the whole column
- 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 , the rectangles under row 's histogram are exactly the all-ones rectangles whose bottom row is . Taking the best over all rows covers every rectangle, in time in total.
How many maximal empty rectangles can points in a box have?
- At most
- in the worst case
- in the worst case, but in expectation for uniformly random points
- Exponentially many
Show the answer
C. in the worst case, but in expectation for uniformly random points
Naamad, Lee and Hsu (1984) proved the upper bound and gave quadratic examples, such as two staircases of points; for random points the expected number is . That is why their algorithm is fast on typical inputs.
Why does every algorithm for the largest all-ones rectangle in an matrix need time in the worst case?
- Because the cells must first be sorted
- Because the number of rectangles is
- It does not: suffices with prefix sums
- 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 ; 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.