← Back to Algorithms, page 2

algorithms-0038 · Hard senior

Largest rectangle in a histogram: find the area of the largest rectangle that fits under a bar chart of unit-width bars.

For each bar, the widest rectangle using its full height stretches until the nearest shorter bar on each side. Keep a stack of indices with increasing heights; when a shorter bar arrives, pop taller bars, because the arriving bar is their right limit and the new top of the stack is their left limit. A sentinel 0 at the end flushes the stack. O(n) time.

Full answer

Problem

Given bar heights, each bar width 1, return the largest rectangle area within the histogram.

Example: [2, 1, 5, 6, 2, 3] gives 10 (heights 5 and 6, width 2, height 5).

Constraints: 0 <= len(heights) <= 10^5, 0 <= heights[i] <= 10^4.

Brute force

For every pair (i, j), the rectangle height is the minimum bar in between; keep a running minimum as j grows: O(n^2). The test uses this as the reference.

Optimal approach

Scan heights + [0] with a stack of indices whose heights increase. For each i with height h:

  1. While the top bar is at least as tall as h: pop top.
    • Its right limit is i (the first shorter bar to the right).
    • Its left limit is the new stack top plus 1, or 0 if the stack is empty.
    • Area is heights[top] x (i - left).
  2. Push i.

The final 0 is shorter than every bar, so it pops everything that remains.

Why it works

The largest rectangle has some bar as its shortest bar, and for that bar the best rectangle extends to the nearest strictly shorter bar on each side. The increasing stack means the element below top is the nearest bar to the left that is shorter (or equal, which is fine, since an equal bar to the left will produce the full-width rectangle when it is popped later). The bar that causes the pop is the first one to the right that is not taller. So every bar's maximal rectangle is computed when it is popped.

Complexity

O(n) time: each index is pushed and popped once. O(n) space.

Code

python
def largest_rectangle(heights):
    """Largest rectangle in a histogram using a monotonic increasing stack. O(n)."""
    stack = []                                   # indices with increasing heights
    best = 0
    for i, h in enumerate(heights + [0]):        # sentinel 0 flushes the stack
        while stack and heights[stack[-1]] >= h:
            top = stack.pop()
            left = stack[-1] + 1 if stack else 0  # first bar not shorter, to the left
            width = i - left
            best = max(best, heights[top] * width)
        stack.append(i)
    return best


def brute(heights):
    best = 0
    for i in range(len(heights)):
        low = heights[i]
        for j in range(i, len(heights)):
            low = min(low, heights[j])
            best = max(best, low * (j - i + 1))
    return best


if __name__ == "__main__":
    for f in (largest_rectangle, brute):
        assert f([2, 1, 5, 6, 2, 3]) == 10
        assert f([2, 4]) == 4
        assert f([]) == 0
        assert f([0]) == 0
        assert f([3, 3, 3]) == 9
        assert f([6, 2, 5, 4, 5, 1, 6]) == 12
    print("all tests passed")

Save as a38_histogram.py and run python3 a38_histogram.py. It prints all tests passed (Python 3.13.5).

Edge cases

Empty list returns 0. Bars of height 0 split the histogram. All equal heights give h x n. Strictly increasing heights are all handled by the sentinel. Concatenating [0] creates a new list; the code uses it only for iteration and still reads heights[top] from the original.

Pattern

Monotonic stack for nearest smaller element on both sides. The maximal rectangle of 1s in a binary matrix applies this row by row. Related: sum of subarray minimums and trapping rain water with a stack.

python
def largest_rectangle(heights):
    """Largest rectangle in a histogram using a monotonic increasing stack. O(n)."""
    stack = []                                   # indices with increasing heights
    best = 0
    for i, h in enumerate(heights + [0]):        # sentinel 0 flushes the stack
        while stack and heights[stack[-1]] >= h:
            top = stack.pop()
            left = stack[-1] + 1 if stack else 0  # first bar not shorter, to the left
            width = i - left
            best = max(best, heights[top] * width)
        stack.append(i)
    return best


def brute(heights):
    best = 0
    for i in range(len(heights)):
        low = heights[i]
        for j in range(i, len(heights)):
            low = min(low, heights[j])
            best = max(best, low * (j - i + 1))
    return best


if __name__ == "__main__":
    for f in (largest_rectangle, brute):
        assert f([2, 1, 5, 6, 2, 3]) == 10
        assert f([2, 4]) == 4
        assert f([]) == 0
        assert f([0]) == 0
        assert f([3, 3, 3]) == 9
        assert f([6, 2, 5, 4, 5, 1, 6]) == 12
    print("all tests passed")

Increasing stack with a 0 sentinel; an O(n^2) running-minimum reference passes the same tests.

Complexity

Time: O(n). Space: O(n). Each bar's area is computed once, when it is popped.

By level

Fresher: Gives the O(n^2) solution and explains the idea of extending each bar to the nearest shorter bars. Should give the O(n^2) running-minimum solution.

Mid: Implements the stack version with correct width formula and sentinel, and handles equal heights. Explains the sentinel at the end.

Senior: Solves the matrix version, compares with the two-pass left and right arrays approach, and generalises the nearest-smaller pattern. Applies the method to the binary matrix problem.

Key points

  • Each bar's best rectangle extends to the nearest shorter bars
  • Increasing stack gives the left limit
  • The bar causing the pop is the right limit
  • Sentinel 0 flushes remaining bars
  • O(n) time

Common mistakes

  • Computing width with the popped index instead of the new stack top
  • Forgetting to flush the stack at the end
  • Mishandling equal heights without reasoning about them
  • Assuming the rectangle must start at a bar's own index

Follow-ups

  • How do you find the maximal rectangle of 1s in a binary matrix?
  • How would you compute the sum of minimums of all subarrays?
  • Can you do it with precomputed left and right smaller arrays?

Tips

  • Explain "each bar as the shortest" first
  • Draw the stack on the example
  • Explain the sentinel

Evaluation rubric

  • Correct stack algorithm and widths
  • Correct handling of ends and equal heights
  • Correct complexity
  • Clear justification