Largest Rectangle in Histogram

Find the area of the largest rectangle that fits under a row of bars, using a stack of rising bars.

Given an array heights that describes a histogram, a bar chart whose bars stand side by side, each 1 unit wide, return the area of the largest rectangle that fits inside the histogram.

Histogram with bars 2, 1, 5, 6, 2, 3
Example 1
Input: heights = [2, 1, 5, 6, 2, 3]
Output: 10
Explanation: the bars of height 5 and 6 together hold a rectangle of height 5 and width 2.
The largest rectangle, area 10, shaded over the bars 5 and 6
Example 2
Input: heights = [2, 4]
Output: 4
Explanation: a rectangle of height 2 across both bars and the bar of height 4 on its own both give 4.
Solution

The Idea

Think of the histogram as a row of buildings, each one unit wide, with roofs at the heights 2, 1, 5, 6, 2 and 3. You want to paint the largest rectangle you can across their fronts. It must stand on the ground and must never go above the roof of any building it covers.

Try a few choices. A rectangle across all six buildings can only be 1 high, because of the building of height 1, so its area is 6. Across the 5 and the 6 it can be 5 high, which gives 5 × 2 = 10. Across the 5, 6, 2 and 3 it drops to 2 high, for 2 × 4 = 8. Each time, the shortest building under the rectangle sets its height.

Six bars already allow 21 different stretches of neighbouring bars, and 100,000 bars allow about five billion. Do we really have to try every stretch?

No, if we turn the question around. Every rectangle's height is set by the shortest bar under it, so ask instead, for each bar: if this bar is the shortest one, how wide can the rectangle be? It can grow to both sides until it meets a bar that is shorter. Look at the picture below.

The histogram 2, 1, 5, 6, 2, 3 at positions 0 to 5. A rectangle of height 5 covers positions 2 and 3, area 10. It stops at the first shorter bar on the left, height 1 at position 1, and the first shorter bar on the right, height 2 at position 4.

Take the bar of height 5 at position 2. On its left, position 1 holds a bar of height 1, labelled the first shorter bar on the left, so the rectangle cannot grow that way. On its right, the 6 is taller, so the rectangle passes over it. It stops at position 4, the first shorter bar on the right, of height 2. That leaves width 2 and area 5 × 2 = 10.

Doing the same for each of the six bars gives six areas, and the largest of them is the answer. So the whole problem comes down to one question per bar: where is the first shorter bar on each side?

Solution Approach

Turning that idea into code means settling three things: how to find each bar's shorter neighbours faster than the simple way, how to work out the width once they are known, and what to do with bars that have no shorter bar on their right.

Finding the shorter neighbours

How do we find the first shorter bar on each side? The simple way walks left and right from every bar until it meets one. That is correct but slow. When the heights only rise, such as 1, 2, 3, 4, 5, each walk to the right runs to the end, and 100,000 bars need about five billion steps.

A faster way reads the bars once, from left to right, and keeps aside the bars that are still waiting for a shorter bar on their right. They wait on a stack: a pile where items are added and removed only at the top, so the last one added comes off first. In Java, an ArrayDeque works as a stack with push (add on top), pop (take off the top) and peek (look at the top without taking it off).

When a new bar arrives, every waiting bar that is taller than it has just found its first shorter bar on the right: the new bar. Those bars come off the stack, and then the new bar goes on. Since every taller bar leaves before a bar is added, the heights on the stack rise from bottom to top. A stack kept in rising (or falling) order like this is often called a monotonic stack.

Working out the width

The popped bar knows its first shorter bar on the right, but where is the one on its left? It is the bar right below it on the stack. Any bar that stood between the two was removed earlier, when a shorter bar came after it, so those bars are taller than the popped bar and do not stop its rectangle.

Follow the example when position 4, of height 2, arrives. The stack holds positions 1, 2 and 3, with heights 1, 5 and 6. The 6 is taller than 2, so position 3 comes off. Its first shorter bars are position 4 on the right and position 2 on the left, so its width is 4 - 2 - 1 = 1 and its area 6.

Next, position 2 (height 5) comes off, with position 1 now below it: width 4 - 1 - 1 = 2, area 10. The bar of height 1 at position 1 is not taller than 2, so it stays, and position 4 goes on top.

In both cases the width is the right neighbour's position minus the left neighbour's position, minus 1. If the stack is empty after a pop, no bar on the left is shorter, and the rectangle reaches back to position 0. Using -1 as the left neighbour's position keeps the same rule working.

Two bars of the same height can sit on the stack together, because only taller bars come off. The upper one then measures a rectangle that is too narrow. The lower one is measured later and covers the full width, so the largest area is still found.

Bars left at the end

What about bars that never meet a shorter bar on their right? After the last bar of the example, the stack still holds positions 1, 4 and 5, and their rectangles reach the right edge. Pretending there is one more bar of height 0 after the last one takes care of them. It is shorter than every bar, so it pops them all with the same code, and its position acts as their first shorter bar on the right.

Java Solution

The method largestRectangleArea works in these steps:

  1. First, create an empty ArrayDeque named stack, which holds positions of bars, and set best, the largest area found so far, to 0.
  2. Read the bars with a for loop in which i goes from 0 up to n, one step past the last position, n - 1. The current height h is heights[i], or 0 when i equals n: that is the extra bar of height 0.
  3. Inside, a while loop pops every position on the stack whose bar is taller than h. For each one, height is that bar's height, left is the position now on top of the stack (or -1 if the stack is empty), and width is i - left - 1.
  4. Compare height * width with best and keep the larger one.
  5. After the while loop, push i onto the stack. Once the for loop has passed the extra bar, best holds the answer.

The main method runs both examples, three bars of equal height, bars that only rise, a short bar between two taller ones, and an empty array.

Java
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;

public class LargestRectangleInHistogram {

    public static int largestRectangleArea(int[] heights) {
        int n = heights.length;
        Deque<Integer> stack = new ArrayDeque<>();      // positions, heights rising bottom to top
        int best = 0;
        for (int i = 0; i <= n; i++) {
            int h = (i == n) ? 0 : heights[i];          // a last bar of height 0 empties the stack
            while (!stack.isEmpty() && heights[stack.peek()] > h) {
                int height = heights[stack.pop()];      // this bar's rectangle is now closed
                int left = stack.isEmpty() ? -1 : stack.peek();  // first shorter bar on the left
                int width = i - left - 1;               // i is the first shorter bar on the right
                best = Math.max(best, height * width);
            }
            stack.push(i);
        }
        return best;
    }

    public static void main(String[] args) {
        int[][] tests = {
            {2, 1, 5, 6, 2, 3},
            {2, 4},
            {3, 3, 3},
            {1, 2, 3, 4, 5},
            {2, 1, 2},
            {}
        };
        for (int[] heights : tests) {
            String input = Arrays.toString(heights);
            System.out.println(input + " -> " + largestRectangleArea(heights));
        }
    }
}

Running it prints:

Output
[2, 1, 5, 6, 2, 3] -> 10
[2, 4] -> 4
[3, 3, 3] -> 9
[1, 2, 3, 4, 5] -> 9
[2, 1, 2] -> 3
[] -> 0

Look at the line for [3, 3, 3]: 9 is the full width of 3 times the height of 3. The three equal bars all wait on the stack, and the lowest of them, popped last, measures the whole row. [1, 2, 3, 4, 5] also gives 9, from the bars 3, 4 and 5 at height 3. There nothing comes off the stack until the extra bar of height 0 arrives.

[2, 1, 2] gives 3: the bar of height 1 is the only one whose rectangle spans all three positions. The empty array gives 0, because the loop's only step pushes position 0 and pops nothing.

The extra bar of height 0 is easy to leave out. A version whose loop stops at i < n prints 0 for [2, 4], because no bar there is followed by a shorter one, so nothing is ever measured. The same version still prints 10 for Example 1, since 10 is found when the bar of height 2 arrives, which hides the bug.

The original implementation, LargestRectangleInHistogram.java, is on GitHub.

Complexity

The work is one pass over the bars, plus the pops from the stack.

  • Time: O(n), because each of the n positions is pushed once and popped at most once. So over all n + 1 steps of the for loop, the while loop pops at most n times in total.
  • Space: O(n) for the stack, which ends up holding every position when the heights only rise, as in [1, 2, 3, 4, 5].

Running this on each row of a grid of 0s and 1s, with each bar's height counting the 1s stacked above it, solves Maximal Rectangle.