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.
- rows == matrix.length
- cols == matrix[i].length
- 1 <= rows, cols <= 200
- matrix[i][j] is '0' or '1'.
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).
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.
Approach
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).
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.
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.
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.
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.
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.
Code in Python, C++ and Java
Common pitfalls
Comparing a cell with the number 1
heights[j] = heights[j] + 1 if row[j] == 1 else 0
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'
if row[j] == "1":
heights[j] += 1heights[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
best = max(best, height * (j - popped))
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.
Edge cases
'1' anywhereEvery height is 0, so every measured area is 0 and the answer is 0.
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.
Complexity
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.