← Whiteboard questions

Largest Rectangle In Histogram

Find the biggest rectangle that fits under the bars

DSA, Hard, Stack

Which structure or algorithm, and what does it cost.

A list heights gives the heights of bars that stand side by side, each one unit wide. Choose any run of neighbouring bars. A rectangle over that run can be as tall as the shortest bar in the run and as wide as the run is long. Return the largest area that any such rectangle can have.

Examples

Input heights = [3, 1, 4, 4, 2]
Output 8
Why the two bars of height 4 make a rectangle 2 wide and 4 tall. Using all five bars is limited by the bar of height 1, which gives only 5.
Input heights = [2, 3, 4]
Output 6
Why the heights only rise, so no bar is ever blocked on its right and every rectangle runs to the end: 2 tall by 3 wide, or 3 tall by 2 wide.
Input heights = [0, 7, 0]
Output 7
Why a bar of height 0 limits any run that contains it. The best rectangle is the single bar of 7.

Constraints

Your answer must contain

Target Aim for O(n) time and O(n) memory.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

In any rectangle, one bar is the shortest. Imagine that bar is fixed. How far can the rectangle reach to the left and to the right?

Hint 2 the approach

A bar reaches until a shorter bar blocks it on each side. Find a way to learn the blocking bars without a new scan for every bar.

Hint 3 the key step

Keep a stack of rising bars. A shorter bar ends the rectangles of the taller bars on top. After they leave, how far back can the new bar reach?

Walkthrough

Full walkthrough brute force to best

Brute force

Try every run of bars. For each pair of ends, take the shortest bar in the run times the run's width. Keeping a running shortest bar while the right end moves right makes this O(n^2) time. With 50,000 bars that is about 1.25 billion runs.

Best method

Each best rectangle has a shortest bar, so find how far each bar can reach. Keep a stack of pairs (start, height), where start is the leftmost position the bar's height reaches. Heights rise from the bottom of the stack to the top. Walk the bars in order. A bar of height h pops every stacked bar that is at least as tall. A popped bar cannot reach past the current position, so its rectangle is its height times (current position minus its start). The new bar takes the start of the last bar popped, because it can reach back through all of them. Then push it. A final bar of height 0 pops everything that is left. Each bar is pushed once and popped once, so the time is linear.

Hand trace

Run on [3, 1, 4, 4, 2] with a final 0 added. Position 0 (3): push (0, 3). Position 1 (1): pop (0, 3), area 3 * (1 - 0) = 3. Push (0, 1), because the new bar reaches back to 0. Position 2 (4): push (2, 4). Position 3 (4): pop (2, 4), area 4 * (3 - 2) = 4. Push (2, 4). Position 4 (2): pop (2, 4), area 4 * (4 - 2) = 8, the best so far. Push (2, 2). Final 0 at position 5: pop (2, 2), area 2 * (5 - 2) = 6. Then pop (0, 1), area 1 * (5 - 0) = 5. The best area is 8.

Code

def largest_rectangle(heights):
    best = 0
    stack = []                      # (start, height): bars that can still reach further right
    for i, h in enumerate(heights + [0]):
        start = i
        while stack and stack[-1][1] >= h:
            s, height = stack.pop()
            best = max(best, height * (i - s))
            start = s
        stack.append((start, h))
    return best

Time and memory

O(n) time, because each bar is pushed once and popped once. O(n) memory, because the stack can hold every bar, for example when the heights only rise.

Common mistakes

  • Pushing the new bar with its own position as the start. After popping taller bars it must take the start of the last one popped, or its rectangle comes out too narrow.
  • Stopping at the last bar. Bars still on the stack have rectangles that reach the right end, so add a final bar of height 0 to pop them.
  • Using the number of bars on the stack as the width. The width is a distance in positions: the current position minus the start.
  • Using two pointers from the ends, as for a water container. Here every bar between the ends limits the height, not only the two end bars.

Related problems

More Stack problems
Largest Rectangle In Histogram: walkthrough and solution