LeetCode #85 Hard

Maximal Rectangle

Maximal Rectangle is LeetCode 85 (Hard). You get a grid of '0' and '1' characters. Return the area of the largest rectangle, with sides along the grid lines, that contains only '1' cells.

  • The grid is at most 200 × 200, so trying every pair of corners and checking the cells inside is far too slow.
  • The cells are characters, not numbers, in the Python, C++ and Java signatures.
Constraints
  • rows == matrix.length
  • cols == matrix[i].length
  • 1 <= rows, cols <= 200
  • matrix[i][j] is '0' or '1'.
monotonic-stackmatrixdp
Open on LeetCode ↗
02

Intuition

Fix the row that holds a rectangle's bottom edge and count, for each column, the unbroken run of '1's ending on that row. Those counts form a histogram, and every all-1 rectangle with its bottom edge on this row fits under the bars. So the best rectangle for this bottom row is the largest rectangle in that histogram, and since every rectangle has some bottom row, the best over all rows is the answer.

A bar's widest rectangle stops at the nearest lower bar on each side. A stack of column indices with rising heights finds both of those lower bars in one left-to-right scan, so each row costs O(cols).

How to spot this pattern

The largest all-1 rectangle in a grid is the matrix form of Largest Rectangle in Histogram: build a histogram per row, then reuse the monotonic-stack pass.

03

Approach

Try it first

Before reading on, write down the column heights for each row of a small grid by hand, and check that the answer is the biggest rectangle under one of those histograms. Then decide what a bar on a stack is waiting for. Aim for O(rows × cols).

1

Grow the heights for this row

For each column, set heights[j] to heights[j] + 1 under a '1' and to 0 under a '0'. A '0' cuts the column, so no rectangle that ends on this row can reach above it.

2

Scan the bars with a rising stack

Walk the columns left to right, keeping a stack of column indices whose heights rise from bottom to top. A bar waits on the stack until a bar no taller than it shows up, because until then its rectangle can still stretch to the right.

3

Pop a bar and measure its rectangle

While heights[j] is not above the top bar's height, pop the top. Its rectangle has the popped height and runs right to column j − 1 and left to just after the new top, the nearest lower bar. The width is j − left − 1, with left = −1 when the stack is empty.

4

Push the current column

After the pops, push j. Every bar still on the stack is lower than column j, so the heights on the stack keep rising from bottom to top, and the bar under each entry is always its nearest lower bar to the left.

5

Flush the stack at the end of the row

Run j one step past the last column with a height of 0. No real bar is below 0, so every bar left on the stack is popped and measured. Keep the largest area over all rows.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def maximalRectangle(self, matrix: list[list[str]]) -> int:
▶3 cols = len(matrix[0])
▶4 heights = [0] * cols
▶5 best = 0
▶6 for row in matrix:
▶7 for j in range(cols):
▶8 heights[j] = heights[j] + 1 if row[j] == "1" else 0
▶9 stack = []
▶10 for j in range(cols + 1):
▶11 h = heights[j] if j < cols else 0
▶12 while stack and heights[stack[-1]] >= h:
▶13 height = heights[stack.pop()]
▶14 left = stack[-1] if stack else -1
▶15 best = max(best, height * (j - left - 1))
▶16 stack.append(j)
▶17 return best
gridheights, row 01011111111col 00col 11col 2stack of columnsheight × widthbest0row 0 heights: 1, 0, 1
row0
heights[1, 0, 1]
Row 0 becomes the floor of a histogram. Each column's bar counts the 1s standing in an unbroken run that ends on this row; the 0 in column 1 cuts that column back to height 0. Any all-1 rectangle whose bottom edge is on row 0 fits under these bars.
gridheights, row 01011111111col 00col 11col 2stack of columns0height × widthbest0push column 0 (height 1) to wait
stack[0]column indices
Column 0 has height 1 and the stack was empty. Its rectangle could still stretch right, so it waits until a bar no taller than it arrives.
gridheights, row 01011111111col 00col 11col 2stack of columnsheight × width1×1=1best1pop column 0 → 1 × 1 = 1, new best
height1column 0
width1columns 0 to 0
best1
Pop column 0 (height 1) because column 1 is not taller (0), so its rectangle cannot stretch further right. On the left it reaches the grid edge, since the stack is now empty. 1 × 1 = 1, the largest so far.
gridheights, row 01011111111col 00col 11col 2stack of columns1height × widthbest1push column 1 (height 0) to wait
stack[1]column indices
Column 1 has height 0 and the stack was empty. Its rectangle could still stretch right, so it waits until a bar no taller than it arrives.
gridheights, row 01011111111col 00col 11col 2stack of columns12height × widthbest1push column 2 (height 1) to wait
stack[1, 2]column indices
Column 2 has height 1, taller than column 1 below it on the stack. Its rectangle could still stretch right, so it waits until a bar no taller than it arrives.
gridheights, row 01011111111col 00col 11col 2stack of columns1height × width1×1=1best1end of row: pop column 2 → 1 × 1 = 1
height1column 2
width1columns 2 to 2
best1
Pop column 2 (height 1) because the row has ended, so its rectangle cannot stretch further right. On the left it reaches just past column 1, the lower bar now on top of the stack. 1 × 1 = 1, which only ties the best.
gridheights, row 01011111111col 00col 11col 2stack of columnsheight × width0×3=0best1end of row: pop column 1 → 0 × 3 = 0
height0column 1
width3columns 0 to 2
best1
Pop column 1 (height 0) because the row has ended, so its rectangle cannot stretch further right. On the left it reaches the grid edge, since the stack is now empty. 0 × 3 = 0, not above the best of 1.
gridheights, row 11011111112col 01col 12col 2stack of columnsheight × widthbest1row 1 heights: 2, 1, 2
row1
heights[2, 1, 2]
Row 1 becomes the floor of a histogram. Each column's bar counts the 1s standing in an unbroken run that ends on this row. Any all-1 rectangle whose bottom edge is on row 1 fits under these bars.
gridheights, row 11011111112col 01col 12col 2stack of columns0height × widthbest1push column 0 (height 2) to wait
stack[0]column indices
Column 0 has height 2 and the stack was empty. Its rectangle could still stretch right, so it waits until a bar no taller than it arrives.
gridheights, row 11011111112col 01col 12col 2stack of columnsheight × width2×1=2best2pop column 0 → 2 × 1 = 2, new best
height2column 0
width1columns 0 to 0
best2
Pop column 0 (height 2) because column 1 is not taller (1), so its rectangle cannot stretch further right. On the left it reaches the grid edge, since the stack is now empty. 2 × 1 = 2, the largest so far.
gridheights, row 11011111112col 01col 12col 2stack of columns1height × widthbest2push column 1 (height 1) to wait
stack[1]column indices
Column 1 has height 1 and the stack was empty. Its rectangle could still stretch right, so it waits until a bar no taller than it arrives.
gridheights, row 11011111112col 01col 12col 2stack of columns12height × widthbest2push column 2 (height 2) to wait
stack[1, 2]column indices
Column 2 has height 2, taller than column 1 below it on the stack. Its rectangle could still stretch right, so it waits until a bar no taller than it arrives.
gridheights, row 11011111112col 01col 12col 2stack of columns1height × width2×1=2best2end of row: pop column 2 → 2 × 1 = 2
height2column 2
width1columns 2 to 2
best2
Pop column 2 (height 2) because the row has ended, so its rectangle cannot stretch further right. On the left it reaches just past column 1, the lower bar now on top of the stack. 2 × 1 = 2, which only ties the best.
gridheights, row 11011111112col 01col 12col 2stack of columnsheight × width1×3=3best3end of row: pop column 1 → 1 × 3 = 3, new best
height1column 1
width3columns 0 to 2
best3
Pop column 1 (height 1) because the row has ended, so its rectangle cannot stretch further right. On the left it reaches the grid edge, since the stack is now empty. 1 × 3 = 3, the largest so far.
gridheights, row 21011111113col 02col 13col 2stack of columnsheight × widthbest3row 2 heights: 3, 2, 3
row2
heights[3, 2, 3]
Row 2 becomes the floor of a histogram. Each column's bar counts the 1s standing in an unbroken run that ends on this row. Any all-1 rectangle whose bottom edge is on row 2 fits under these bars.
gridheights, row 21011111113col 02col 13col 2stack of columns0height × widthbest3push column 0 (height 3) to wait
stack[0]column indices
Column 0 has height 3 and the stack was empty. Its rectangle could still stretch right, so it waits until a bar no taller than it arrives.
gridheights, row 21011111113col 02col 13col 2stack of columnsheight × width3×1=3best3pop column 0 → 3 × 1 = 3
height3column 0
width1columns 0 to 0
best3
Pop column 0 (height 3) because column 1 is not taller (2), so its rectangle cannot stretch further right. On the left it reaches the grid edge, since the stack is now empty. 3 × 1 = 3, which only ties the best.
gridheights, row 21011111113col 02col 13col 2stack of columns1height × widthbest3push column 1 (height 2) to wait
stack[1]column indices
Column 1 has height 2 and the stack was empty. Its rectangle could still stretch right, so it waits until a bar no taller than it arrives.
gridheights, row 21011111113col 02col 13col 2stack of columns12height × widthbest3push column 2 (height 3) to wait
stack[1, 2]column indices
Column 2 has height 3, taller than column 1 below it on the stack. Its rectangle could still stretch right, so it waits until a bar no taller than it arrives.
gridheights, row 21011111113col 02col 13col 2stack of columns1height × width3×1=3best3end of row: pop column 2 → 3 × 1 = 3
height3column 2
width1columns 2 to 2
best3
Pop column 2 (height 3) because the row has ended, so its rectangle cannot stretch further right. On the left it reaches just past column 1, the lower bar now on top of the stack. 3 × 1 = 3, which only ties the best.
gridheights, row 21011111113col 02col 13col 2stack of columnsheight × width2×3=6best6end of row: pop column 1 → 2 × 3 = 6, new best
height2column 1
width3columns 0 to 2
best6
Pop column 1 (height 2) because the row has ended, so its rectangle cannot stretch further right. On the left it reaches the grid edge, since the stack is now empty. 2 × 3 = 6, the largest so far.
gridheights, row 21011111113col 02col 13col 2stack of columnsheight × widthbest6every row done → answer 6
return6
Every row has served as the bottom edge, so every rectangle has been measured. The largest, highlighted in the grid, covers rows 1 to 2 and columns 0 to 2: area 6.
05

Common pitfalls

Comparing a cell with the number 1

✗ Wrong
heights[j] = heights[j] + 1 if row[j] == 1 else 0
✓ Right
heights[j] = heights[j] + 1 if row[j] == "1" else 0

The cells are the characters '0' and '1'. In Python "1" == 1 is always false, and in C++ or Java '1' is the number 49, so every height stays 0. For [["1"]] the code returns 0 instead of 1.

Adding 1 without resetting on a '0'

✗ Wrong
if row[j] == "1":
    heights[j] += 1
✓ Right
heights[j] = heights[j] + 1 if row[j] == "1" else 0

A '0' must cut the column. Without the reset, the count from above it survives, so a rectangle can pass straight through the '0'. For the column [["1"], ["0"], ["1"]] the last height is 2 and the code returns 2 instead of 1.

Measuring the width from the popped column

✗ Wrong
best = max(best, height * (j - popped))
✓ Right
left = stack[-1] if stack else -1
best = max(best, height * (j - left - 1))

A popped bar can stretch left past its own column, over earlier bars that were popped because they were not lower. Only the bar below it on the stack is lower. For [["1", "1", "1"]] the wrong width gives 1 each time instead of 3.

06

Edge cases

No '1' anywhere

Every height is 0, so every measured area is 0 and the answer is 0.

A single row

Every height is 0 or 1, so the answer is the length of the longest run of '1's, found by the same stack pass.

07

Complexity

Time
O(rows × cols)
Space
O(cols)
Each row updates cols heights, and in the stack pass each column is pushed once and popped once. The heights array and the stack each hold at most cols + 1 entries.
08

Maximal Rectangle FAQ

How does this relate to Largest Rectangle in Histogram?

That problem, LeetCode 84, is the inner loop here. This page runs the same stack pass once per row, on a histogram built from the grid, and keeps the best area across rows.

Why not use the Maximal Square trick?

The square solution takes the smallest of three neighbouring answers plus 1, which works because a square has one side length. A rectangle's width and height change independently, so no single number per cell captures it. In [["1", "1", "1", "1"]] the largest square is 1, but the largest rectangle is 4.

Is there a version without a stack?

Yes. For each row, keep three arrays: the height of each column, and how far left and right that bar can stretch given the cells above. Both bounds update in one sweep each way per row, and the area is height × (right − left). It is also O(rows × cols) but needs three arrays and careful bound updates.