KatInterview

Largest Block Under a Skyline of Columns

Stacks & QueuesAuto-graded · 23 test cases
MediumAuto-gradedStacks & Queuesmonotonic-stackarrayhistogram

Last updated

Compute the largest rectangle that fits under a row of unit-width columns, testing monotonic stack usage and boundary reasoning over contiguous ranges.

You are given a list columns of n non-negative integers describing a skyline. Each entry is the height of one column, and every column is exactly 1 unit wide. Columns sit side by side with no gaps, in the order given.

You may pick any non-empty run of adjacent columns and draw an axis-aligned rectangle that rests on the baseline and stays fully inside the chosen columns. For a run from index i to index j (inclusive), the tallest rectangle that fits has:

  • height equal to the smallest value among columns[i..j], and
  • width j - i + 1.

Its area is height multiplied by width.

Return the largest area achievable over all possible runs.

Notes:

  • A run of a single column is allowed.
  • If every column has height 0, the answer is 0.

Constraints

  • 1 <= n <= 100000
  • 0 <= columns[i] <= 1000000000
  • The answer fits in a 64-bit signed integer.

Examples

Example 1

Input: largest_skyline_rectangle([2, 1, 5, 6, 2, 3])

Output: 10

Example 2

Input: largest_skyline_rectangle([2, 4])

Output: 4

Hints

Hint 1

Any rectangle is limited by its shortest column. Instead of enumerating all runs, ask: for each column, how far can a rectangle extend left and right while that column stays the minimum?

Hint 2

Checking every pair (i, j) is O(n^2). To find the nearest strictly shorter column on each side in one pass, keep a stack of indices whose heights never decrease from bottom to top.

Hint 3

When a new column is shorter than the one on top of the stack, the top column cannot extend further right, so pop it and compute its area. Its left edge is one past the new stack top (or 0 if empty). Append a height-0 sentinel to flush the remaining indices.