Largest Rectangle in Histogram

Hard

Topics
ArrayStackMonotonic Stack

Given an array heights of bar heights (each width 1), return the area of the largest rectangle that fits in the histogram.

Example 1

215623
Bars are the histogram heights; the answer is the largest axis-aligned rectangle that fits entirely under this outline.
Input:  heights = [2,1,5,6,2,3]
Output: 10

Example 2

24
Input:  heights = [2,4]
Output: 4

Constraints

  • 1 <= heights.length <= 10^5
  • 0 <= heights[i] <= 10^4
Editorial — intuition, approach, complexity and pitfalls

Intuition

For each bar the widest rectangle of its height extends until a shorter bar on either side. A monotonic increasing stack lets you find, at the moment a bar is popped, exactly that left and right boundary.

Approach

  1. Keep a stack of indices with increasing heights.
  2. When the current bar is shorter than the stack top, pop it; its height times the width between the new top and current index is a candidate area.
  3. Use a trailing 0-height sentinel to flush the stack.

Dry Run

nums = [2, 1, 5, 6, 2, 3], with a 0 appended as a sentinel so the stack always drains

i=0  h=2   push                      stack=[0]
i=1  h=1   pop 0: height 2, width 1  best=2      push   stack=[1]
i=2  h=5   push                      stack=[1, 2]
i=3  h=6   push                      stack=[1, 2, 3]
i=4  h=2   pop 3: height 6, width 1  best=6
           pop 2: height 5, width 2  best=10     push   stack=[1, 4]
i=5  h=3   push                      stack=[1, 4, 5]
i=6  h=0   pop 5: height 3, width 1
           pop 4: height 2, width 4
           pop 1: height 1, width 6                     stack=[]

answer 10   (heights 5 and 6, two bars wide)

Complexity

  • Time — O(n): each bar is pushed and popped once.
  • Space — O(n): the stack.

Common Pitfalls

  • Compute width from the index below the popped bar, not the popped index itself.

Full Solution — all languages

class Solution:
    def largestRectangleArea(self, nums):
        stack = []
        best = 0
        heights = nums + [0]
        for i, h in enumerate(heights):
            while stack and heights[stack[-1]] >= h:
                height = heights[stack.pop()]
                width = i if not stack else i - stack[-1] - 1
                if height * width > best:
                    best = height * width
            stack.append(i)
        return best
SensAI
Beta
Tap the mic to stop voice mode