Skip to content

Largest Rectangle in Histogram

Find the biggest rectangle in a bar chart by letting each bar find its nearest shorter bars with a stack.

HardStacks
Solve on LeetCode

The problem

You get an array heights where each value is the height of a bar of width 1, and the bars stand side by side to form a histogram. Return the area of the largest rectangle that fits entirely inside the histogram. The rectangle covers a run of neighbouring bars, so its height is limited by the shortest bar in that run.

Input heights = [2, 5, 4, 5, 1]

Output 12

The bars 5, 4 and 5 are all at least 4 tall, so a rectangle of height 4 and width 3 fits.

Input heights = [9, 2, 2, 2, 2, 2]

Output 12

The tall bar alone gives only 9, but height 2 across all six bars gives 12.

Key constraint: Up to 100,000 bars, so trying every pair of left and right edges (O(n^2)) is too slow.

How to spot the pattern

  • For each bar you need its nearest shorter bar on the left and on the right.
  • The value of a range is limited by its minimum, so you want, for every bar, the widest range in which it is the minimum.
  • The input is large, so you need about O(n), not O(n^2).

The idea

In the best rectangle, some bar is the shortest one, and the rectangle stretches out from that bar until a shorter bar blocks it on each side. So for every bar you need its nearest shorter neighbour on both sides. A stack of indexes with increasing heights finds both in one pass: when a shorter bar arrives, every taller bar it pops has just found its right boundary, and the index left below it on the stack is its left boundary.

Brute force: For every left edge, extend to the right while tracking the minimum height, which tries all O(n^2) ranges.

Step by step

  1. 1Walk through the bars from left to right, plus one extra bar of height 0 at the end so every bar gets popped.
  2. 2While the current bar is shorter than the bar on top of the stack, pop that index; its height is the rectangle's height.
  3. 3The rectangle runs from just after the new top of the stack to just before the current index i, so its width is i - top - 1, or i if the stack is now empty.
  4. 4Update the best area with height times width, then push the current index.
  5. 5Return the best area after the extra bar has flushed the stack.

See the pattern move

The stacks pattern on a small example. Step through it, or press play.

Code

class Solution:
    def largestRectangleArea(self, heights: List[int]) -> int:
        n = len(heights)
        stack = []  # indexes of bars, heights increasing from bottom to top
        best = 0
        for i in range(n + 1):
            current = heights[i] if i < n else 0  # the extra 0 flushes the stack
            while stack and heights[stack[-1]] > current:
                height = heights[stack.pop()]
                left = stack[-1] if stack else -1  # nearest shorter bar on the left
                best = max(best, height * (i - left - 1))
            stack.append(i)
        return best

Complexity

Time

O(n)

Space

O(n)

Each index is pushed once and popped once; the stack holds all n indexes when the heights keep increasing.

Watch out for

  • Forgetting to flush the stack at the end: without the extra height 0, rising bars like [1, 2, 3] are never popped and never measured.
  • Measuring the width from the popped index instead of from the new top of the stack, which misses the taller bars to the left that were popped earlier.
  • Assuming the answer uses the tallest bar: a wide, short rectangle often wins, as in [9, 2, 2, 2, 2, 2].

Follow-up questions

How do you find the largest rectangle of 1s in a binary matrix?

Treat each row as the floor of a histogram, where a column's height is the number of 1s stacked directly above it, ending at that row. Run this algorithm once per row, for O(rows * cols) in total. That is Maximal Rectangle.

Is there a version that is easier to debug?

Use two passes with the same kind of stack: one finds each bar's nearest shorter bar on the left, the other on the right. Then the answer is the largest heights[i] * (right[i] - left[i] - 1). It is the same idea with two extra arrays.

In Hinglish

Har bar se poocho: agar main sabse chhota hoon toh left aur right mein kitna phail sakta hoon? Stack se dono taraf ke chhote padosi ek hi pass mein mil jaate hain.

Related problems