Skip to content
Problem 84 · LeetCode 84(opens in a new tab)

Largest Rectangle in Histogram

HardArrays

A bar chart is drawn from the list heights: bar i stands heights[i] units tall, every bar is 1 unit wide, and the bars sit side by side with no gaps.

Find the biggest rectangle you can draw that lies completely inside the bars, with its base on the ground. Return its area.

Example 1

Input:  heights = [3, 1, 4, 5, 2]
Output: 8
Why:    the bars 4 and 5 hold a 2-wide rectangle 4 tall
2 more examples and the constraints

Example 2

Input:  heights = [2, 2, 2]
Output: 6
Why:    all three bars together, 3 wide and 2 tall

Example 3

Input:  heights = [0, 7]
Output: 7
Why:    the 0 bar adds nothing; the 7 bar alone wins

Constraints

  • 1 ≤ length of heights ≤ 100,000
  • 0 ≤ heights[i] ≤ 10,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Every range of barsO(n²)
  2. Monotonic stackO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100,000 barsVerdict
Every range of barsO(n²)
Mention it, then move on
Monotonic stackO(n)
Best; each bar pushed and popped once

n = number of bars.

Edge cases to test

  • One bar. [5] gives 5. The flush at the end still scores it.
  • Bars of height 0. [0, 0] gives 0. A 0 bar splits the chart in two.
  • Heights only rise. [1, 2, 3, 4, 5] never pops until the end, so the final flush does all the work. The answer is 9 (3 × 3).
  • Equal heights. [2, 2, 2] gives 6. Popping on >= means the last equal bar scores the full width.
  • Largest sizes. 100,000 bars of 10,000 make 1,000,000,000, which still fits in a 32-bit int.

Common mistakes

  • Forgetting the bars still on the stack at the end, so a rising chart returns too little.
  • Measuring the width from the popped index itself instead of from the bar now under it in the stack.
  • Storing heights instead of indices on the stack, so the width cannot be worked out.

How to talk through it

  1. 1Clarify. Can a bar be 0 tall? How many bars at most? Must the rectangle sit on the ground?
  2. 2Give the brute force. Every run of bars, scored by its shortest bar times its width. O(n²), too slow for 100,000.
  3. 3Flip the question. Fix the bar that sets the height. Its rectangle spans to the nearest shorter bar on each side.
  4. 4Code the stack. Keep heights rising. A shorter bar pops the taller ones; the new top is the left wall, i is the right wall.
  5. 5Test out loud. Run a rising chart, equal bars and a single bar before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?