Coding interview problems › Stack & Monotonic Stack
📚 Stack & Monotonic Stack Hard
Largest Rectangle in Histogram
Largest Rectangle in Histogram explained: an increasing stack finds where each bar's rectangle ends on both sides in O(n). Tested Python, live visual.
Also searched as: maximum area histogram · largest area under histogram stack · max rectangle in histogram
Try it live Free
Stacks & the Monotonic Stack
Practise the monotonic stack mode on Next Greater Element and Daily Temperatures first; this problem is the same push-and-pop pattern, except each pop also measures a rectangle.
The problem
Given the heights of bars in a histogram, each bar 1 unit wide, find the area of the largest rectangle that fits entirely inside the histogram.
Bars of heights 5 and 6 give a rectangle of height 5 and width 2.
The key insight
The best rectangle uses some bar as its shortest bar, and stretches left and right until it hits a shorter one. Keep a stack of bar indices with increasing heights. When a shorter bar arrives, every taller bar on top has just found its right boundary, and the bar below it on the stack is its left boundary, so you can compute its full rectangle as you pop it.
Step-by-step approach
- Append a bar of height 0 at the end so every bar eventually gets popped.
- Scan bars left to right with index
i, keeping a stack of indices of increasing height. - While the current bar is shorter than the bar on top, pop index
top; its height ish = heights[top]. - Its rectangle spans from just after the new stack top to just before
i: width isiif the stack is empty, elsei - stack[-1] - 1. Update the best area withh * width. - Push
iand continue. Return the best area.
Python solution
def largest_rectangle_area(heights):
best = 0
stack = [] # indices, heights increasing
for i, h in enumerate(heights + [0]): # sentinel 0 flushes the stack
while stack and heights[stack[-1]] > h:
height = heights[stack.pop()]
left = stack[-1] if stack else -1 # last bar shorter than height
best = max(best, height * (i - left - 1))
stack.append(i)
return bestComplexity
Each bar is pushed and popped exactly once, and each pop computes one rectangle in constant time.
Common mistakes
- Forgetting the sentinel bar of height 0, so bars still on the stack at the end are never measured.
- Computing the width as
i - topinstead of using the new stack top as the left boundary, which undercounts rectangles that extend left past popped bars. - Reading
heights[i]for the sentinel index without extending the list, which goes out of range.
Frequently asked questions
What is the time and space complexity?
O(n) time because each bar is pushed and popped once, and O(n) space for the stack.
How does this help with Maximal Rectangle in a binary matrix?
Treat each row as the floor of a histogram where a column's height is the number of consecutive 1s above it. Run this algorithm on every row, for O(rows · cols) total.
Is there a divide-and-conquer solution?
Yes: the best rectangle either uses the shortest bar across the full width or lies entirely to its left or right. It averages O(n log n) but degrades to O(n²) on sorted input, so the stack is preferred.
Why do equal heights not break the algorithm?
With the strict comparison, an equal bar stays on the stack and the earlier one is measured later with the correct, wider span. The maximum area comes out right either way.
Preparing for placements?
Take the 2-minute readiness check to find your weak patterns, then follow the placement path from DSA core to system design.
All coding interview problems More Stack & Monotonic Stack Stacks & the Monotonic Stack lab Placement prep guides
Problem statements on this site are written in our own words. Problem names are the common names used across interview-prep communities; BitBootcamp is an independent learning platform and is not affiliated with LeetCode or any company that asks these questions.