☰ All problems

35. Largest Rectangle in Histogram

HardArrayStack

A histogram is drawn with bars of width 1 standing side by side; bar i has height heights[i].

Return the area of the largest rectangle that fits entirely inside the histogram. The rectangle must be axis-aligned and can span several adjacent bars, but it cannot rise above the shortest bar it covers.

Example 1
Input: heights = [3,1,4,4,2]
Output: 8

Explanation: The two bars of height 4 form a 4 × 2 rectangle. Spanning the last three bars only gives 2 × 3 = 6.

Example 2
Input: heights = [5]
Output: 5
Example 3
Input: heights = [2,2,2,2]
Output: 8

Constraints

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

Every optimal rectangle is as tall as some bar i. For that bar, how far can the rectangle stretch left and right?

💡 Hint 2

It stretches until the first strictly shorter bar on each side. Finding those boundaries naively is O(n²).

💡 Hint 3

Keep a stack of indices with increasing heights. When a shorter bar arrives, it is the right boundary of every taller bar you pop, and the new stack top is the left boundary.

/**
 * @param {number[]} heights
 * @return {number}
 */
function largestRectangleArea(heights) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc