Skip to content

visual walkthrough

Largest Rectangle in Histogram

HardMonotonic StackReported at: AmazonMicrosoftMeta+5

The defining Hard monotonic-stack problem.

Solve on LeetCode

The idea

The best rectangle's height is that of one of the bars, and it stretches as far as the neighbours are at least that tall. A stack of bars in increasing height finds both limits at once.

When a shorter bar arrives, every taller bar on the stack ends here; each pop gives one candidate rectangle.

Complexity

approachtimespace
Stretch from every barO(n²)O(1)
Monotonic stackO(n)O(n)

More walkthroughs