hardStackAmazonGoogleMicrosoft
Skyline Rectangle Scan
A row of unit-width buildings forms a histogram. Find the biggest axis-aligned rectangle that fits entirely inside the skyline.
Given a `heights` array (unit width per bar), return the area of the largest rectangle bounded by the bars.
Choose approach
Input
2
1
5
6
2
3
top
1/14
Narrationstep 1 of 14
Monotonic increasing stack of bar indices. A shorter incoming bar pops taller bars and resolves their widest spanning rectangle.
Variables
best=0
How to think about it
- For every bar there's a maximal rectangle whose height = that bar's height.
- That rectangle extends until a shorter bar on each side.
- A monotonic increasing stack gives the first shorter bar to the left for free.
- A shorter incoming bar triggers the right-boundary pops.
- Append a sentinel height 0 at the end to flush all remaining bars.
Edge cases to catch in interview
- All equal heights — area = n × h.
- Monotonic increasing — resolved during the sentinel flush.
- Single bar — area = height.
Examples
Example 1
10{"heights":[2,1,5,6,2,3]}
Bars 2 and 3 at height 5 give 5 × 2 = 10.
Example 2
4{"heights":[2,4]}
Try your own input
SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed