FAANGPrep Sprint
Largest Rectangle in Histogram
Find the area of the largest rectangle in the histogram.
Problem Understanding
heights lists the bars of a histogram from left to right, each bar one unit wide. Return the area of the biggest rectangle that fits entirely inside the bars.
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
[2, 1, 5, 6, 2, 3]
BASE -1
heights
0
1
2
3
4
5
stack · indices
TOP · base
h
—
Area
—
Best
0
Start the stack with -1: the left edge for a bar with nothing shorter before it
Next
i = 0: h = 2
Heights
Visualize how we pop bars when a shorter one appears, calculating potential areas.
