Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Book a call

Coding · Stack

Largest rectangle in a bar chart

Hard · Target 25 minutes · Stack· Type asked at

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.

Where people lose marks

  • Computing the width as i − top. The rectangle for the popped bar starts just after the bar now below it on the stack, not at the popped bar itself, because every bar in between was taller.
  • Forgetting the bars still on the stack at the end. Without the sentinel of height 0, the rising run [1, 2, 3, 4, 5] never pops anything and the answer 9 is missed.
  • Using an empty stack as a left limit of 0 but writing the width as i − left − 1. With no bar on the left the rectangle starts at index 0, so the width is i.
  • Overflow in languages with 32-bit ints if the limits are larger than these: the area can reach height × n. Use 64-bit arithmetic when in doubt.
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.