AlgoTales · Roadmap

Largest rectangle in histogram

Advanced · 13 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Given bars of different heights standing side by side, this finds the biggest rectangle that fits inside them. A stack tracks bars in rising order, and when a lower bar arrives it closes off the taller bars and measures their rectangles.

Practical use cases

  • Web app: Widest free block in a bar chart. A room-booking dashboard shows, for each hour, how many rooms are free as bar heights. The manager wants the largest block of time where at least some number of rooms is free together. The stack method finds the biggest such block in one pass, instead of trying every start and end hour.
  • Web app: Biggest banner space on a page layout. An ad tool looks at how tall the free space is in each column of a page and wants the largest rectangle that could hold a banner. Reading the columns as a histogram gives the answer in a single sweep.
  • System: Grid problems and packing. A well-known extension turns a grid of ones and zeros into rows of bar heights to find the biggest all-ones rectangle. The same pattern is used in layout and space-packing tools, where one stack pass replaces a slow search over every possible rectangle.

The story: The Biggest Banner

The mohalla was painting a giant banner along a wall of tall and short sticks, standing side by side like the bars of a chart: heights 2, 1, 5, 6, 2, 3. Mira wanted the largest rectangle of colour that fits entirely within the sticks. She could choose any run of neighbouring sticks, but the rectangle can be only as tall as the shortest stick in the run.

The slow way: for each stick, stretch left and right as far as no shorter stick blocks, then measure the area. That works, but it keeps re-walking the same ground. Kabir whispered, "Remember the monotonic stack? For each stick, we need the nearest shorter stick on the left and on the right."

So Mira kept a stack of sticks in increasing height order. Each new stick that is taller simply joins. But when a shorter stick arrives, the taller stick on top has found its right wall. Its left wall is the stick just below it on the stack, because everything between them was taller. Now the width is known, and so is the area: height times width.

At the very end, Mira added an imaginary stick of height 0 to force out all the remaining ones. The largest area ever seen, 10 from the 5 and 6 sticks, was the winning banner. This is a famous and difficult problem, but it is really a stack plus one sentence: "when a bar is popped, we know exactly how wide it can be."

How to spot this problem, and where you need it

You have bars side by side and want the largest rectangle that can sit within them, and trying every possible pair of start and end bars is far too slow.

Signs you need it

  • The problem says "largest rectangle", "maximum area under a histogram", "biggest empty block" or "widest span at a given height".
  • You try every pair of bars and compute the minimum height between them, and the work explodes with the number of bars.
  • Data can be described as columns of different heights, like availability per hour or free space per column.

Where to use it in a project

  • Scheduling and capacity dashboards looking for the longest period with enough free capacity.
  • Layout, ad placement and space-packing tools on web pages.
  • Grid puzzles that can be turned into rows of bar heights.

The solution

Walk through the bars keeping a stack of bars in rising height order. When a bar is shorter than the top of the stack, pop the top: it cannot extend further right. Its rectangle uses its own height, and its width reaches from just after the new top of the stack to the current bar. Track the best area. After the last bar, empty the stack the same way.

Payoff: Before: checking every pair of 10,000 bars, about 50 million combinations. After: each bar pushed and popped once, about 20,000 steps.

Explain it like I am 8

Stand colourful sticks side by side. Hold a flat ruler across a few of them: the ruler can only sit as high as the shortest stick under it. You want the ruler position that covers the most area. A stack remembers the sticks that can still stretch to the right. When a shorter stick shows up, the taller ones can stretch no further.

How it works, step by step

  1. Keep a stack of bar positions whose heights are increasing from bottom to top.
  2. For each bar (and a final imaginary bar of height 0 at the end), while the top bar is at least as tall as the current one, pop it.
  3. For the popped bar, its right edge is just before the current position. Its left edge is just after the new top of the stack (or position 0 if the stack is empty).
  4. Area = popped bar's height × width, where width = current position - left edge. Keep the maximum.
  5. Push the current bar (except for the imaginary one) and continue. The answer is the best area seen.

The code in four languages

PHP

<?php
// Largest rectangle in a histogram using a stack of increasing bar positions.
function largestRectangle(array $heights): int {
    $n = count($heights);
    $stack = [];                                     // positions, heights increasing
    $best = 0;

    for ($i = 0; $i <= $n; $i++) {
        $cur = ($i === $n) ? 0 : $heights[$i];       // imaginary bar of height 0 at the end

        // a shorter bar arrives: taller bars on top can stretch no further
        while ($stack && $heights[end($stack)] >= $cur) {
            $height = $heights[array_pop($stack)];
            $left = $stack ? end($stack) + 1 : 0;    // first position it can stretch to
            $best = max($best, $height * ($i - $left));
        }
        $stack[] = $i;
    }
    return $best;
}

echo largestRectangle([2, 1, 5, 6, 2, 3]) . PHP_EOL;   // 10

JavaScript

// Largest rectangle in a histogram using a stack of increasing bar positions.
function largestRectangle(heights) {
  const n = heights.length;
  const stack = [];                                  // positions, heights increasing
  let best = 0;

  for (let i = 0; i <= n; i++) {
    const cur = i === n ? 0 : heights[i];            // imaginary bar of height 0 at the end

    // a shorter bar arrives: taller bars on top can stretch no further
    while (stack.length && heights[stack[stack.length - 1]] >= cur) {
      const height = heights[stack.pop()];
      const left = stack.length ? stack[stack.length - 1] + 1 : 0;   // first position it can stretch to
      best = Math.max(best, height * (i - left));
    }
    stack.push(i);
  }
  return best;
}

console.log(largestRectangle([2, 1, 5, 6, 2, 3]));   // 10

Java

import java.util.*;

public class Main {
    // Largest rectangle in a histogram using a stack of increasing bar positions.
    static int largestRectangle(int[] heights) {
        int n = heights.length;
        Deque<Integer> stack = new ArrayDeque<>();       // positions, heights increasing
        int best = 0;

        for (int i = 0; i <= n; i++) {
            int cur = (i == n) ? 0 : heights[i];         // imaginary bar of height 0 at the end

            // a shorter bar arrives: taller bars on top can stretch no further
            while (!stack.isEmpty() && heights[stack.peek()] >= cur) {
                int height = heights[stack.pop()];
                int left = stack.isEmpty() ? 0 : stack.peek() + 1;   // first position it can stretch to
                best = Math.max(best, height * (i - left));
            }
            stack.push(i);
        }
        return best;
    }

    public static void main(String[] args) {
        System.out.println(largestRectangle(new int[]{2, 1, 5, 6, 2, 3}));   // 10
    }
}

Go

package main

import "fmt"

// largestRectangle uses a stack of increasing bar positions.
func largestRectangle(heights []int) int {
	n := len(heights)
	var stack []int // positions, heights increasing
	best := 0

	for i := 0; i <= n; i++ {
		cur := 0 // imaginary bar of height 0 at the end
		if i < n {
			cur = heights[i]
		}

		// a shorter bar arrives: taller bars on top can stretch no further
		for len(stack) > 0 && heights[stack[len(stack)-1]] >= cur {
			height := heights[stack[len(stack)-1]]
			stack = stack[:len(stack)-1]
			left := 0 // first position it can stretch to
			if len(stack) > 0 {
				left = stack[len(stack)-1] + 1
			}
			best = max(best, height*(i-left))
		}
		stack = append(stack, i)
	}
	return best
}

func main() {
	fmt.Println(largestRectangle([]int{2, 1, 5, 6, 2, 3})) // 10
}

Time: O(n) · Extra space: O(n). Each bar is pushed once and popped once. Checking every pair of left and right ends would take O(n²).

Watch out for

  • Forgetting the final imaginary bar of height 0. Without it the bars left on the stack are never measured.
  • Using the popped position for the width. The left edge is the new stack top plus one, and the right edge is the current position minus one.
  • Forgetting the empty-stack case: then the popped bar was the shortest so far and stretches all the way back to position 0.

Quick check

  1. What is the largest rectangle in heights [2, 1, 5, 6, 2, 3]?
    • 10
    • 12
    • 8
  2. When is a bar popped from the stack?
    • When a taller bar arrives
    • When a shorter (or equal) bar arrives
    • Only at the very end
  3. Why add an imaginary bar of height 0 at the end?
    • To double the area
    • To make the histogram longer
    • To pop and measure everything still on the stack