Stack
Hard
Largest Rectangle in Histogram
Find the area of the largest rectangle in the histogram.
10 min read
Solve on LeetCodeProblem Understanding
Given an array heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.
Example:
- Input:
[2, 1, 5, 6, 2, 3] - Output:
10(The rectangle from index 2 to 3 with height 5 has area 5 * 2 = 10).
Algorithm Strategy
We use a Monotonic Increasing Stack.
Core Idea:
For each bar h at index i, if we know the first bar to the left that is smaller (left_limit) and the first bar to the right that is smaller (right_limit), then the maximum width for a rectangle with height h is right_limit - left_limit - 1.
One-Pass Logic:
- Maintain a stack of indices with increasing heights.
- When we encounter a bar
h[i]smaller thanh[stack.top()], it meansh[i]is the Right Limit forh[stack.top()]. - Pop
top. Now the New Top of the stack is the Left Limit for the popped bar. - Calc Area:
height * (i - stack.top() - 1). - Repeat until stack rule is satisfied, then push
i.
Interactive Visualization
Step 1 / 1
Empty Stack
Top Index: -1Initializing...
1x
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.ON THIS PAGE
- Problem Understanding
- Algorithm Strategy
- Interactive Visualization
- Dry Run
- Edge Cases & Common Mistakes
- Solution
Stop Guessing, Start Mastering.
Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.
