Largest Rectangle in Histogram

Hard#84increasing stack

You get the heights of bars standing side by side, each one unit wide. Find the area of the largest rectangle that fits inside them. Our example: [2, 5, 6, 3, 4, 1] gives 12, height 3 over the bars at indices 1 to 4.

input
heights: the heights of bars standing side by side, each one unit wide.
returns
The area of the largest rectangle that fits inside the bars.
constraints
  • 1 ≤ heights.length ≤ 10⁴
  • 0 ≤ heights[i] ≤ 10⁴
our 13 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[]} heights
 * @return {number}
 */
function largestRectangleArea(heights) {

}
Ctrl ↵
format
reset

saved in this browser

13 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more monotonic stack problems

Pattern “Monotonic stack” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.