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
Example 1
Output: 10
Explanation: the bars of height 5 and 6 together hold a rectangle of height 5 and width 2.
Example 2
Output: 4
Explanation: a rectangle of height 2 across both bars and the bar of height 4 on its own both give 4.
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.
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 ArrayDequepushpoppeek
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
- First, create an empty
namedArrayDeque , which holds positions of bars, and setstack , the largest area found so far, to 0.best - Read the bars with a
loop in whichfor goes from 0 up toi , one step past the last position,n . The current heightn - 1 ish , or 0 whenheights[i] equalsi : that is the extra bar of height 0.n - Inside, a
loop pops every position on the stack whose bar is taller thanwhile . For each one,h is that bar's height,height is the position now on top of the stack (or -1 if the stack is empty), andleft iswidth .i - left - 1 - Compare
withheight * width and keep the larger one.best - After the
loop, pushwhile onto the stack. Once thei loop has passed the extra bar,for holds the answer.best
The main
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:
[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][1, 2, 3, 4, 5]
[2, 1, 2]
The extra bar of height 0 is easy to leave out. A version whose loop stops at i < n[2, 4]
The original implementation,
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
loop, thefor loop pops at most n times in total.while - 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