CodeArchon

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.

1def skyline_rect_scan(heights: list[int]) -> int:
2 st: list[int] = []
3 best = 0
4 for i in range(len(heights) + 1):
5 curr = 0 if i == len(heights) else heights[i]
6 while st and heights[st[-1]] > curr:
7 h = heights[st.pop()]
8 left = st[-1] if st else -1
9 best = max(best, h * (i - left - 1))
10 st.append(i)
11 return best
Variables
best=0

How to think about it

  1. For every bar there's a maximal rectangle whose height = that bar's height.
  2. That rectangle extends until a shorter bar on each side.
  3. A monotonic increasing stack gives the first shorter bar to the left for free.
  4. A shorter incoming bar triggers the right-boundary pops.
  5. 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 110
{"heights":[2,1,5,6,2,3]}

Bars 2 and 3 at height 5 give 5 × 2 = 10.

Example 24
{"heights":[2,4]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed