← DSA
HARD

Largest Rectangle in Histogram

PracticeNeetCode ↗LeetCode ↗

Given an array heights representing a histogram's bar heights, where each bar has width 1, return the area of the largest rectangle that fits entirely within the histogram.

Example

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

Key Pointers

Step-by-Step Analysis

  1. Create an empty stack (holding (start_index, height) pairs) and set max_area to 0.
  2. For each index i, height h: while the stack's top has a height greater than h, pop it, compute its area as height * (i - start_index), update max_area, and remember its start_index as the new bar's own start.
  3. Push (start, h) onto the stack.
  4. After the loop, pop everything remaining, treating the width as extending to the end of the array (len(heights) as the right boundary), updating max_area each time.

Complexity

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

Code

def largestRectangleArea(heights: list[int]) -> int:
    stack = []  # (start_index, height) pairs
    max_area = 0

    for i, h in enumerate(heights):
        start = i
        while stack and stack[-1][1] > h:
            index, height = stack.pop()
            max_area = max(max_area, height * (i - index))
            start = index
        stack.append((start, h))

    for index, height in stack:
        max_area = max(max_area, height * (len(heights) - index))

    return max_area

Code Explanation

How the solution above works, piece by piece.

  1. The stack holds (start_index, height) pairs with heights increasing from bottom to top.
  2. When bar h is lower than the top, the top bar's rectangle can't extend past i. Pop it and measure height * (i - index).
  3. start = index: the new, shorter bar can extend left to where the popped bar began, so it's pushed with that earlier start.
  4. After the loop, the bars still on the stack extend all the way to the end: measure them with len(heights) - index.
  5. Each bar is pushed and popped once: O(n) time, O(n) space.

Visual Walkthrough

Running it on heights = [2, 1, 5, 6, 2, 3]:

Histogram with the largest rectangle of area 102156235 × 2 = 10i=1: pop height 2 from 0 → 2×1 = 2i=4: pop height 6 from 3 → 6×1 = 6i=4: pop height 5 from 2 → 5×2 = 10end: height 1 from 0 → 1×6 = 6end: height 2 from 2 → 2×4 = 8end: height 3 from 5 → 3×1 = 3
The stack keeps bars in increasing height. When a shorter bar arrives, taller bars can't extend any further right, so they are popped and their rectangle is measured. Popping 5 at i = 4 gives 5 × 2 = 10, the answer.
largest rectangle

Video Explanation

NeetCode — LeetCode 84