Maximal Rectangle

hard

Given a binary matrix matrix filled with 0s and 1s, find the largest rectangle containing only 1s and return its area.

Hints

Process the matrix row by row and turn each row into a histogram.
heights[j] = consecutive 1s in column j ending at the current row (reset on a 0).
The biggest all-1s rectangle bottoming out on a row is the largest rectangle in that histogram.

Common doubts

Every maximal 1-rectangle has a bottom row; over that row, its columns are exactly the histogram bars, so its area is a rectangle in that histogram.
A 0 breaks the vertical run of 1s in that column, so the histogram bar there restarts from zero.
No — update it incrementally in O(cols) per row, so the whole thing is O(rows x cols).

Interview follow-ups

That has a simpler O(rows x cols) DP: dp[i][j] = 1 + min of the three neighbors when the cell is 1.
Track, when you update the best area in the histogram routine, the row, the popped height, and the left/right boundaries.

Fun facts

  • Reducing a 2D problem to a stack of 1D histograms is a hallmark technique — it turns an intimidating matrix problem into one you already know.
  • This is the standard follow-up to Largest Rectangle in Histogram in interviews.

Asked at

AmazonGoogleMicrosoft
Frequently Sometimes Occasionally
Example 1
Input: matrix = [[1,0,1,0,0],[1,0,1,1,1],[1,1,1,1,1],[1,0,0,1,0]]
Output: 6
The largest all-1s rectangle is the 2x3 block in the middle, area 6.
Example 2
Input: matrix = [[0]]
Output: 0
No 1s, so the area is 0.
Constraints

- 1 <= rows, cols <= 200 - matrix[i][j] is 0 or 1

Solve this problem →