Skip to content
Work Free practice Coding course Blog Method Results Why me About Enquire Book a call

Coding · Stack

Largest rectangle in a bar chart

Hard · Target 25 minutes · Stack · Type asked atAmazonBloomberg

An array heights gives the heights of bars of width 1 standing side by side. Return the area of the largest rectangle that fits entirely inside the bars.

Examples

InputOutputWhy
heights = [2, 1, 5, 6, 2, 3]10Height 5 across the bars 5 and 6: width 2.
heights = [2, 4]4Either the single bar of 4, or height 2 across both.
heights = [5, 4, 3, 2, 1]9Height 3 across the first three bars.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 0 ≤ heights[i] ≤ 10⁴

Hints

Hint 1

The best rectangle has some shortest bar, and it stretches as far left and right as it can without meeting anything shorter. So for each bar, what are the two limits?

Hint 2

For each bar you need the nearest shorter bar on its left and on its right. That is a "nearest smaller element" question, twice.

Hint 3

Keep indices with increasing heights on a stack. When a shorter bar arrives, it is the right limit for every taller bar it pops, and the bar below each popped one on the stack is its left limit. Add a bar of height 0 at the end to flush the stack.

Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.