Skip to content

visual walkthrough

Maximal Rectangle

HardMonotonic Stack per RowReported at: GoogleAmazonApple

Reduces a 2D grid to repeated histogram problems.

Solve on LeetCode

The idea

Every all-1 rectangle has a bottom row. Standing on that row, the columns above look like a bar chart: each bar is how many 1s are stacked up to here.

So solve "largest rectangle in a histogram" (a monotonic stack) once per row, updating the bars as you go down.

Complexity

approachtimespace
Grow from every cornerO(R² · C²)O(1)
Row by row histogramsO(R · C)O(C)

More walkthroughs