Largest Rectangle in Histogram

HardMonotonic Stack🧩 Monotonic StackLeetCode #84 ↗Updated

Problem

A histogram is given as heights, where every bar has width 1 and bars stand side by side. Find the area of the largest axis-aligned rectangle that fits completely inside the histogram.
Input[2,1,5,6,2,3]Output10
Input[2,4]Output4

1 ≤ n ≤ 105  ·  0 ≤ heights[i] ≤ 104

Try it yourself

Java
class Solution {
    public int largestRectangleArea(int[] heights) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
The best rectangle is limited by its shortest bar. So for every bar, stretch it left and right until the first strictly shorter bar on each side: area = h[i] × (right - left - 1). A monotonic stack finds both walls.
PatternMonotonic Stack

Instinct Each element needs its nearest bigger or smaller neighbour (next warmer day, span, widest bar) - keep a sorted stack of waiting indices.

Memory hack Tall people block the view - a newcomer kicks out everyone shorter waiting behind, and each kicked-out person just found their answer.

Open the Monotonic Stack guide →

Approaches

Brute ForceAll Ranges with Running Minimum

Time O(n2)Space O(1)

Fix a left edge i and extend the right edge j one bar at a time, tracking the minimum height of [i..j]. The rectangle over that range has area min × (j - i + 1).

Java
public int largestRectangleArea(int[] heights) {
    int maxArea = 0;
    for (int i = 0; i < heights.length; i++) {
        int minHeight = Integer.MAX_VALUE;
        for (int j = i; j < heights.length; j++) {
            minHeight = Math.min(minHeight, heights[j]);
            maxArea = Math.max(maxArea, minHeight * (j - i + 1));
        }
    }
    return maxArea;
}

Simple, but ~5·109 steps at n = 105 — TLE.

At a glance

LevelApproachTimeSpace
Brute ForceAll Ranges with Running MinimumO(n2)O(1)
BetterNearest Smaller on Each Side (Two Passes)O(n)O(n)
OptimalOne-Pass Increasing Stack + SentinelO(n)O(n)
Common pitfalls
  • Forgetting to process bars left on the stack at the end — the sentinel handles it.
  • Width off-by-one: it is i - left - 1, with left = -1 on an empty stack.
  • Measuring width from the popped index instead of the new stack top.
Interview tips
  • Reframe first: “each bar as the shortest one — how far can it extend?”
  • Present the two-pass version, then fuse it into one pass with the sentinel.
  • Walk through [2,1,5,6,2,3]; it exercises every branch.
Pattern
Monotonic increasing stack → span/area problems bounded by the nearest smaller element on both sides.
My notes saved in this browser