Skip to problem
←

Largest Rectangle in Histogram

Hard 0 attempts

Given adjacent histogram bars of width 1, find the maximum area of an axis-aligned rectangle lying entirely under the bars.

A rectangle spans consecutive bars, and its height cannot exceed the shortest bar in that span. Return the area, not the chosen indices. Zero-height bars cannot be crossed by a positive-height rectangle.

Function contract

heights is a nonempty array of nonnegative bar heights. Every bar has width 1.

Output: Return the largest rectangle area under consecutive bars. Return 0 when all heights are zero.

Example 1

Input
heights = [2,1,5,6,2,3]
Output
10

Explanation: Bars at indices 2 and 3 support a rectangle of height 5 and width 2, giving area 10.

Example 2

Input
heights = [2,2]
Output
4
Visual Aid
The shorter bar limits the height
21562310width 2 × height 5 = area 10

The adjacent bars of heights 5 and 6 support a height-5 rectangle. Each bar contributes one unit of width.

Constraints
  • 1 <= heights.length <= 10^5
  • 0 <= heights[i] <= 10^4

Use a monotonic stack that stores bar indices in non-decreasing height order. When a shorter bar is encountered, pop the stack and compute the area using the popped bar's height as the rectangle height, with width determined by the current index and the new stack top.

javascript
function largestRectangleArea(heights) {
  const stack = [];
  let maxArea = 0;
  const n = heights.length;

  for (let i = 0; i <= n; i++) {
    const h = i === n ? 0 : heights[i];
    while (stack.length && heights[stack[stack.length - 1]] > h) {
      const height = heights[stack.pop()];
      const width = stack.length ? i - stack[stack.length - 1] - 1 : i;
      maxArea = Math.max(maxArea, height * width);
    }
    stack.push(i);
  }

  return maxArea;
}

Time: O(n) Space: O(n)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript