Largest Rectangle in Histogram, explained

The Largest Rectangle in Histogram solution keeps a stack of bar indexes with increasing heights. When a shorter bar arrives, each taller bar popped off the stack has found both of its limits: the new bar on the right and the bar left beneath it on the stack. Its best rectangle is its height times that width. Each bar is pushed and popped once, so the answer comes out in O(n).

By Published 8 min read

What the problem is

You get a list of non-negative heights. Picture each as a bar one unit wide, placed next to each other with no gaps, like a bar chart. A rectangle drawn inside the chart must sit on the baseline and stay under the top of every bar it covers. Return the largest area such a rectangle can have.

Bar charts invented for this page, with answers from the code below
HeightsLargest areaWhere it is
[3, 1, 4, 4, 2]8The two bars of height 4, width 2
[2, 5, 5, 1, 6]10Height 5 across two bars, which narrowly beats the single 6
[4, 4, 4]12The whole chart
[1, 2, 3, 4]6Height 2 across three bars, or height 3 across two
[]0No bars at all
Bar charts invented for this page, with answers from the code below. Scroll sideways on a small screen.

Worth confirming: can heights be zero (yes, usually, and a zero bar splits the chart), how large can the area get (big enough to overflow 32-bit integers in some languages), and is an empty list possible?

Why this one is feared

This problem appears in harder rounds and is widely regarded as one of the toughest stack questions, mostly because the stack solution is hard to invent from scratch. Interviewers rarely expect you to discover it cold. They want to see a clean O(n²) answer, a clear statement of what limits a rectangle, and then either the stack solution or real progress toward it. If you have practiced Daily Temperatures, you already know half of it: that problem finds the next warmer day, and this one finds the next shorter bar on both sides.

The fact everything rests on

Take the best rectangle. Its height must equal the shortest bar it covers, or it could be taller. So for some bar, the best rectangle is exactly that bar's height, stretched left and right until it meets a strictly shorter bar or the edge of the chart. If you can find, for every bar, its nearest shorter neighbor on each side, the answer is the largest height times width among those n candidates.

O(n²): every left edge, every right edge

Fix a left edge. Move the right edge outward one bar at a time and keep the lowest height seen so far; the rectangle between the edges can be that tall. That is n²/2 pairs with O(1) work each. A cruder version that recomputes the minimum for every pair is O(n³), so mention the running minimum to show you are already trimming work.

def biggest_rectangle_slow(heights):
    best = 0
    for left in range(len(heights)):
        lowest = heights[left]
        for right in range(left, len(heights)):
            lowest = min(lowest, heights[right])
            best = max(best, lowest * (right - left + 1))
    return best
Every pair of edges with a running minimum. O(n²).

O(n): a stack of rising bars

Walk left to right, keeping a stack of indexes whose heights rise from bottom to top. When the next bar is at least as tall as the top, push it. When it is shorter, the bar on top can no longer extend to the right, so pop it. Its right limit is the current index. Its left limit is the bar now on top of the stack, which is shorter, because the stack only holds rising heights. The popped bar's rectangle therefore spans from just after that bar up to just before the current one. Keep popping while the top is at least as tall as the current bar, then push the current bar.

A bar of height 0 is appended at the end so that every bar still on the stack gets popped and measured. Without it, a chart that only rises, like [1, 2, 3, 4], would never pop anything.

def biggest_rectangle(heights):
    best = 0
    rising = []  # indexes of bars, heights increasing from bottom to top
    for i, h in enumerate(heights + [0]):  # a zero bar flushes the stack
        while rising and heights[rising[-1]] >= h:
            tall = heights[rising.pop()]
            left_edge = rising[-1] + 1 if rising else 0
            best = max(best, tall * (i - left_edge))
        rising.append(i)
    return best
Python: increasing stack with a zero-height sentinel. O(n) time, O(n) space.
#include <algorithm>
#include <vector>
using namespace std;

long long biggestRectangle(const vector<int>& heights) {
    long long best = 0;
    vector<int> rising;  // indexes with increasing heights
    int n = heights.size();
    for (int i = 0; i <= n; ++i) {
        int h = (i == n) ? 0 : heights[i];
        while (!rising.empty() && heights[rising.back()] >= h) {
            long long tall = heights[rising.back()];
            rising.pop_back();
            int leftEdge = rising.empty() ? 0 : rising.back() + 1;
            best = max(best, tall * (i - leftEdge));
        }
        rising.push_back(i);
    }
    return best;
}
C++: the same stack, with 64-bit areas to avoid overflow.

What happens with equal heights

Both versions pop when the top is greater than or equal to the current bar. With two equal bars, the first one gets popped by the second and measured with a width that stops short. That is fine: the second equal bar stays on the stack, and when it is eventually popped, its left limit reaches past the first one, so the full rectangle is still measured. Using strictly greater also works if you are consistent, but be ready to explain whichever you choose.

Trace on [3, 1, 4, 4, 2]

Push bar 0 (3). Bar 1 (1) pops bar 0: width 1, area 3. Push bar 1. Push bar 2 (4). Bar 3 (4) pops bar 2 with width 1, area 4, and is pushed. Bar 4 (2) pops bar 3: the stack below holds bar 1, so the width runs from index 2 to 3, two bars, area 8. Bar 4 is pushed. The sentinel pops bar 4 (height 2, width 3, area 6) and bar 1 (height 1, width 5, area 5). The best is 8.

Complexity

n is the number of bars
ApproachTimeExtra space
Every pair, minimum recomputedO(n³)O(1)
Every pair, running minimumO(n²)O(1)
Divide at the lowest bar, recurse on each sideO(n log n) on balanced charts, O(n²) on sorted onesO(n) recursion
Increasing stack with sentinelO(n)O(n)
n is the number of bars. Scroll sideways on a small screen.

The stack is linear for the same reason as in Daily Temperatures: each index is pushed once and popped once, so the inner loop's total work across the whole run is at most n.

Edge cases

  • Empty chart: 0.
  • A single bar: its own height.
  • All bars equal: height times the number of bars.
  • Strictly rising heights: nothing pops until the sentinel, which then measures every bar.
  • Zeros in the middle: they pop everything before them, splitting the chart into independent parts.
  • Large heights and many bars: the area can exceed 32-bit range, hence long long in C++.

Where solutions break

  • Computing width as i - popped_index instead of using the bar left on the stack. That misses the stretch to the left of the popped bar.
  • Forgetting the sentinel, so bars still on the stack at the end are never measured.
  • Using the height of the current bar instead of the popped bar when computing area.
  • Pushing heights instead of indexes, which makes widths impossible to compute.

Follow-ups

  • Largest rectangle of 1s in a binary matrix. Treat each row as the base of a histogram whose heights count consecutive 1s above, and run this function on each row. That is O(rows × columns).
  • Return the rectangle's position. Record the left index, right index and height whenever the best area improves.
  • Two passes instead of one. Compute the nearest shorter bar on the left with one stack pass and on the right with another, then combine. Same complexity, sometimes easier to explain.
  • Bars of different widths. Keep prefix sums of widths so the span between two indexes is a subtraction.

Explaining it in the room

Fictional example

How a candidate might present it
Candidate
The best rectangle is as tall as its shortest bar, so for every bar I want the widest rectangle at exactly that height. That's limited by the nearest shorter bar on each side.
Candidate
I keep a stack of indexes with rising heights. When a shorter bar shows up, the top bar has met its right limit, and the bar under it on the stack is its left limit. I compute the area and pop.
Candidate
A zero at the end flushes the stack. Each index goes in and out once, so it's linear, and I'll use 64-bit areas.

Daily Temperatures is the gentler introduction to the same stack. Car Fleet and Min Stack show other stacks that carry more than a single value, and Longest Repeating Character Replacement switches to the window side of this set. The coding problems hub has the full list.

Studying with Natively

This problem is easier to learn with a patient explainer. On a Mac or Windows computer, Natively can read the bar chart prompt from a screenshot in a practice session and walk through why the bar below on the stack marks the left limit, or trace a small example step by step. The transcript and notes it saves let you check later whether your own explanation held together. See how the AI interview assistant works.

Questions people ask

How do you solve Largest Rectangle in Histogram in O(n)?

Keep a stack of bar indexes with increasing heights. When a shorter bar arrives, pop taller bars; each popped bar's rectangle spans from just after the bar below it on the stack to just before the current bar. Append a zero-height bar to flush the stack at the end.

Why does the histogram stack solution need a sentinel?

Bars still on the stack after the last real bar have never been measured. A final bar of height zero is shorter than all of them, so it pops and measures each one.

What is the brute force for Largest Rectangle in Histogram?

Try every left edge, extend the right edge one bar at a time, and keep the lowest height between them. The rectangle at each step is that height times the width, for O(n squared) total.

How is Largest Rectangle in Histogram used in other problems?

The maximal rectangle of 1s in a binary matrix treats each row as a histogram of consecutive 1s above it and runs this algorithm once per row.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP