Scrivio Interview library
Stacks and queuesStacks, queues and heapsReported 19 times · 15 min read · updated 14 November 2026

Given bar heights of a histogram, find the area of the largest rectangle it contains.

1What the question asks, told as a banner on a street

Imagine a street of buildings standing side by side, each one exactly as wide as the others but of different heights. You want to hang the biggest rectangular banner you can across their fronts. The banner must touch the ground, must not stick up above any roof it covers, and may cover several buildings next to each other. A wide banner has to stay low, because the lowest building it covers limits its height. A tall banner can only cover a few tall buildings. Somewhere between those two lies the best banner.

A histogram is that street drawn as a chart. Each bar is a building, one unit wide, and the numbers we are given are the heights. We must find the area of the largest rectangle that fits inside the bars, where area means width times height. The rectangle covers a run of neighbouring bars, and its height can be at most the height of the lowest bar in that run.

Let us use the heights [2, 1, 5, 6, 2, 3] and try a few banners by hand. Across the whole street the lowest bar is 1, so the banner is 6 wide and 1 tall, area 6. Across the bars 5 and 6 it can be 5 tall and 2 wide, area 10. Across 5, 6, 2 and 3 it must drop to 2, but it is 4 wide, area 8. The bar of height 6 alone gives 6. Trying more, nothing beats 10, so the answer is 10.

PictureThe histogram 2, 1, 5, 6, 2, 3 and its largest rectangle

Six bars, each one unit wide. The two marked bars hold the largest rectangle, 5 units tall and 2 wide.

  1. 215623

    1The bars of heights 5 and 6 stand side by side. A rectangle 5 tall fits across both, so its area is 5 x 2 = 10, the answer.

What to assume

Are all bars the same width?
Yes, one unit each.
Can a height be 0?
Yes, and no rectangle can cross such a bar.
Can there be no bars at all?
Yes, and then the answer is 0.
How large can the input be?
Perhaps 100,000 bars of heights up to 10,000, so the largest area, 10^9, still fits in an int, and the method must be close to linear.

A careful candidate asks a few questions first. Are all bars the same width? Yes, one unit each. Can a height be 0? Yes, and such a bar simply splits the street in two, since no banner can cross it. Can there be no bars at all? Yes, and then the answer is 0. How large can the input be? Perhaps 100,000 bars of heights up to 10,000, so the largest area, 10^9, still fits in an int, and the method must be close to linear.

2How to recognise a problem about how far each bar can stretch

When a beginner first reads this question, the natural plan is to try every possible banner: every starting bar, every ending bar, and the lowest bar in between. That plan is correct, and it is the brute force we will write next. But it does not yet use anything special about rectangles, and the question has a hidden shape that is worth finding.

The first clue is the word rectangle together with the rule that it cannot rise above any bar it covers. So a rectangle's height is always the height of its lowest bar. Turn that round: every rectangle has some bar that is its lowest and sets its height. So instead of thinking about ranges, we can think about bars, and ask for each bar how wide a rectangle of exactly its height can be.

The second clue appears as soon as we ask that. A rectangle as tall as bar i can spread left over every bar at least as tall as bar i, and it must stop at the first lower bar. The same holds on the right. So for every bar we want the nearest lower bar on its left and the nearest lower bar on its right. That is the question of the next smaller element, the mirror image of the next greater element.

The third clue is that we need these limits for every bar, not just one. Neighbouring bars often share a limit; in our example, bars 2, 3 and 4 are all stopped on the left by bar 1. When many answers share work like this, a single pass can often produce them all.

These clues lead to the stacks and queues family and a technique called a monotonic stack. A stack is like a pile of plates, where we only add a plate on top, called a push, or take the top one off, called a pop. Monotonic means always moving one way, so our stack keeps bars whose heights rise from bottom to top. The general rule is that whenever the answer depends on how far each element reaches before something smaller stops it, a monotonic stack finds every limit in one pass.

Some patterns look similar and do not fit. The container with the most water uses two pointers moving in from both ends, but there the area depends only on the two end lines; here every bar inside matters. Sorting the bars by height is tempting too, but it forgets which bars stand next to each other, and a rectangle needs neighbours.

3The honest first attempt, trying every range of bars

The first solution anyone writes tries every range of neighbouring bars, from a left edge i to a right edge j. This brute force is a fine start, because it follows the question exactly. To avoid a third loop for finding the lowest bar, we keep a running minimum: as j moves right by one bar, the lowest height so far is either the old lowest or the new bar. The rectangle for range i to j is that lowest height times the width j - i + 1.

Java
static int largestRectangleSlow(int[] heights) {
int best = 0;
for (int i = 0; i < heights.length; i++) { // left edge of the range
int minHeight = Integer.MAX_VALUE;
for (int j = i; j < heights.length; j++) { // right edge of the range
minHeight = Math.min(minHeight, heights[j]); // the lowest bar sets the height
best = Math.max(best, minHeight * (j - i + 1));
}
}
return best;
}

Let us count on the example. With six bars, the left edge 0 has six ranges, the left edge 1 has five, and so on down to one, so there are 6 + 5 + 4 + 3 + 2 + 1 = 21 ranges. Each takes a few simple steps, so the work is about n x n / 2 for n bars, and the time is O(n^2), read as order n squared. For 100,000 bars that is five billion steps, far too slow. The extra space is O(1).

Where is the waste? The range of bars 2 to 3 gives 10, but the brute force also tries bar 2 alone, area 5, and bar 3 alone, area 6. Those ranges could be widened without lowering the rectangle, so they can never be the best. For every bar only one range really matters: the widest one in which that bar is the lowest. That is six candidates instead of 21 ranges. What we lack is a quick way to find each bar's two limits.

4Getting to the one-pass stack, one observation at a time

The picture measures the one rectangle that matters for four of the bars. Each bar spreads sideways over taller bars and stops at the first lower bar on each side. Bar 2, height 5, is stopped by bar 1 and by bar 4 and gives the answer, 10.

Step throughEach bar stretches sideways until a lower bar stops it

The bar being measured is marked now, the bars its rectangle covers are finished, and the lower bars that stop it are marked as compared.

  1. 215623

    1Bar 3 has height 6. Bar 2 on its left, 5, and bar 4 on its right, 2, are both lower, so its rectangle is 1 wide, area 6.

  2. 215623

    2Bar 2 has height 5. It can cover bar 3, which is taller, but bar 1 and bar 4 are lower, so it is 2 wide, area 10.

  3. 215623

    3Bar 4 has height 2. On the left it covers 6 and 5 until bar 1 stops it; on the right it covers 3 to the end. Width 4, area 8.

  4. 215623

    4Bar 1 has height 1, the lowest of all, so nothing stops it. It covers all six bars, width 6, area 6.

So the task is to find, for every bar, its nearest lower bar on the left and on the right. Let us walk from left to right and keep a stack of bar indexes whose heights rise from bottom to top. Why indexes rather than heights? Because a width is a distance between positions, so we need positions, and we can always look up a height from its index.

Now comes the step every beginner gets stuck on, so let us take it slowly. Suppose the stack rises and a new bar i arrives that is lower than or equal to the bar on top. The top bar's rectangle cannot stretch over bar i, so we have found its right limit: the rectangle ends at i - 1. We pop it. Where does it start? Because the stack rises, the bar now on top is the nearest bar to its left that is lower. Every bar between the two was popped earlier by a bar no taller than itself, which means it was at least as tall as the bar we just popped, so the rectangle can cover it. The rectangle therefore starts just after the bar now on top.

That gives a rule we can use at the moment of popping. The popped bar's height is its entry in heights, its left limit is the index now on top, or -1 if the stack is empty, and its width is i - left - 1. We multiply, compare with the best so far, and pop again while the new top is still not lower than bar i. Then we push i. Each bar is measured exactly once, at the moment its right limit arrives.

A beginner might ask what happens to the bars still on the stack when the input runs out. Nothing lower ever arrived to their right, so their rectangles reach the end. A neat way to measure them is to pretend there is one more bar, at index n, with height 0. It is lower than everything, so it pops every remaining bar with right limit n, using the same rule and no extra code.

The most likely mistake is to measure the width from the popped bar's own index, as i minus that index. That forgets that the rectangle may also stretch left over taller bars popped earlier. In our example bar 4, height 2, is popped at i = 6, and 6 - 4 gives a width of 2, but it really covers bars 2 to 5. Only i - left - 1, with left the bar still on the stack, gives the right width, 6 - 1 - 1 = 4.

5Watching the stack measure every bar

The picture plays the one pass on [2, 1, 5, 6, 2, 3]. The bar under i is the one arriving. Bars still on the stack are marked as compared, and when a bar is popped, the bars its rectangle covers are marked as finished, with the panel showing the width rule and the area. In the last frames an empty seventh bar of height 0 stands for the extra step at index n.

Watch the stack heights always rise from bottom to top, and watch each pop measure exactly the rectangle we found by hand in the previous picture.

Step throughOne pass over 2, 1, 5, 6, 2, 3 with a stack of bar indexes

The current bar is under i. Bars still on the stack are marked as compared; the bars a popped rectangle covers are marked as finished.

  1. 215623i
    stack
    0
    best
    0

    1i = 0, height 2. The stack is empty, so nothing can be popped. We push index 0, and the stack holds one bar.

  2. 215623i
    stack
    empty
    popped
    bar 0, height 2
    width
    1 - (-1) - 1 = 1
    area
    2
    best
    2

    2i = 1, height 1, lower than bar 0. Bar 0 cannot stretch past here, so we pop it. Nothing is left on its left, so its width is 1 - (-1) - 1 = 1 and area 2.

  3. 215623i
    stack
    1 2 3
    heights
    1 5 6
    best
    2

    3Then we push index 1. Bars 2 and 3 are taller than the bar below them on the stack, so each is simply pushed in turn.

  4. 215623i
    stack
    1 2
    popped
    bar 3, height 6
    width
    4 - 2 - 1 = 1
    area
    6
    best
    6

    4i = 4, height 2. The top is bar 3, height 6, which is not lower than 2, so we pop it. The new top is bar 2, so its width is 4 - 2 - 1 = 1, area 6.

  5. 215623i
    stack
    1
    popped
    bar 2, height 5
    width
    4 - 1 - 1 = 2
    area
    10
    best
    10

    5The top is now bar 2, height 5, still not lower than 2, so we pop it. The new top is bar 1, so the width is 4 - 1 - 1 = 2 and the area 5 x 2 = 10.

  6. 215623i
    stack
    1 4
    heights
    1 2
    best
    10

    6The top is bar 1, height 1, which is lower than 2, so the popping stops and we push index 4. The stack heights, 1 and 2, still rise.

  7. 215623i
    stack
    1 4 5
    heights
    1 2 3
    best
    10

    7i = 5, height 3, taller than bar 4 on top, so we push it. The input is used up, but bars 1, 4 and 5 have not been measured yet.

  8. 2156230i
    stack
    1 4
    popped
    bar 5, height 3
    width
    6 - 4 - 1 = 1
    area
    3
    best
    10

    8i = 6 is past the end, so we use height 0, drawn as an empty bar. Bar 5 pops first: the top below it is bar 4, so width 6 - 4 - 1 = 1, area 3.

  9. 2156230i
    stack
    1
    popped
    bar 4, height 2
    width
    6 - 1 - 1 = 4
    area
    8
    best
    10

    9Bar 4, height 2, pops next. The bar below it is bar 1, so it stretches over indexes 2 to 5, width 6 - 1 - 1 = 4, area 8, less than 10.

  10. 2156230i
    stack
    empty
    popped
    bar 1, height 1
    width
    6 - (-1) - 1 = 6
    area
    6
    best
    10

    10Bar 1, height 1, pops last. The stack is now empty, so it stretches over the whole histogram, width 6 - (-1) - 1 = 6, area 6.

  11. 215623
    pushes
    7
    pops
    6
    best
    10

    11Every bar has been popped and measured exactly once. The largest area was 10, from bar 2 of height 5 stretched over bars 2 and 3.

Let us read the important frames back. At i = 1 the low bar of height 1 pops bar 0 at once, and with nothing left on the stack bar 0 can only be 1 wide. Bars 2 and 3 then go on top because each is taller than the one before.

The frames at i = 4 are the heart of the method. The bar of height 2 pops bar 3, width 4 - 2 - 1 = 1 and area 6, and then pops bar 2, whose left limit is bar 1, giving width 4 - 1 - 1 = 2 and area 10, the answer. Notice that bar 2's rectangle covers bar 3, which was popped a moment earlier, exactly as the width rule promised.

In the final frames the height-0 bar empties the stack. Bar 4, height 2, measures a width of 4 because bars 2 and 3 to its left were already popped, and bar 1, height 1, covers the whole street. Seven pushes and six pops measured all six bars, and the best stayed 10.

6The complete Java program

Here is the whole program. The for loop runs i from 0 to n inclusive, so that the last round uses the pretend bar of height 0. main runs the example, two bars, three equal bars, a longer histogram, and the empty input, and each comment shows what the line prints.

Java
import java.util.*;
public class LargestRectangle {
static int largestRectangle(int[] heights) {
int n = heights.length, best = 0;
Deque<Integer> stack = new ArrayDeque<>(); // indexes with increasing heights
for (int i = 0; i <= n; i++) {
int h = (i == n) ? 0 : heights[i]; // height 0 at the end flushes the stack
while (!stack.isEmpty() && heights[stack.peek()] >= h) {
int height = heights[stack.pop()]; // this bar's rectangle ends at i - 1
int left = stack.isEmpty() ? -1 : stack.peek(); // first lower bar on the left
best = Math.max(best, height * (i - left - 1));
}
stack.push(i);
}
return best;
}
public static void main(String[] args) {
System.out.println(largestRectangle(new int[] {2, 1, 5, 6, 2, 3})); // 10
System.out.println(largestRectangle(new int[] {2, 4})); // 4
System.out.println(largestRectangle(new int[] {3, 3, 3})); // 9
System.out.println(largestRectangle(new int[] {6, 2, 5, 4, 5, 1, 6})); // 12
System.out.println(largestRectangle(new int[] {})); // 0
}
}

Let us read largestRectangle in the order it runs. We start with best at 0 and an empty stack of indexes. In each round, h is the height of bar i, or 0 when i equals n, which is the pretend bar that empties the stack at the end.

The while loop does the measuring. While the stack is not empty and the bar on top is at least as tall as h, the top bar has met its right limit. We pop it and read its height. Then left is the index now on top, or -1 if the stack is empty, which means the rectangle reaches the start. The width is i - left - 1, and Math.max keeps the larger of the best so far and this area.

After the while loop, every bar on the stack is lower than h, so pushing i keeps the heights rising. When the for loop ends, every bar has been popped and measured once, and best holds the answer.

In main, [2, 4] gives 4. [3, 3, 3] gives 9: because we pop on greater than or equal, the first 3s are measured early with short widths, but the last 3 is measured at the end over all three bars. [6, 2, 5, 4, 5, 1, 6] gives 12, a rectangle 4 tall across 5, 4 and 5. The empty input pops nothing and prints 0.

7How much it costs, and the cases at the edges

Let us count on the example first. The pass pushed seven indexes, the six bars and the pretend bar, and popped six, and each pop did a few simple steps. For n bars there are n + 1 pushes and at most n + 1 pops, so all the while loops together run at most n + 1 times, and the time is O(n). The brute force needed 21 ranges here, and about n x n / 2 in general.

The stack can hold every index when the heights keep rising, so the extra space is O(n). The table compares the approaches, including the two-pass version that finds all left limits and all right limits separately before measuring.

Comparing the approaches
ApproachTimeExtra space
Every range with a running minimumO(n^2)O(1)
Two stack passes for left and right limitsO(n)O(n)
One pass, measuring each bar when it is poppedO(n)O(n)

The edge cases need no special code. An empty array runs only the pretend bar and returns 0. A single bar is popped by the pretend bar with width 1. A bar of height 0 pops everything taller, and its own rectangle has area 0. Equal bars are handled by the last of the run, as [3, 3, 3] showed.

With 100,000 bars of height up to 10,000, the largest area is 10^9, which fits in an int. If the limits were larger, we would compute height * width as a long, because the product could overflow.

8Follow-up questions

How would you find the largest rectangle of 1s in a grid of 0s and 1s?

Treat each row as the ground of a histogram. For each column, the bar height at row r is the number of 1s stacked straight up from row r, which we update from the row above: add 1 for a 1 and reset to 0 for a 0. Then we run the histogram method on each row's heights and keep the best. With R rows and C columns that is O(R x C) time and O(C) space.

Why is the left limit the new top of the stack, and not the bar just before the popped one?

Because the bars between the new top and the popped bar were popped earlier by bars that were lower or equal, so each of them was at least as tall as the popped bar. The popped bar's rectangle can stretch over all of them. The nearest bar that is really lower is the one still sitting on the stack beneath it, so the rectangle starts one index after it.

Is there another way that is easier to explain?

Yes, the two-pass version. One pass from the left with a stack fills an array of nearest lower bars on the left, and one pass from the right fills the nearest lower bars on the right. Then for each bar the area is its height times (right - left - 1). It is also O(n) time, uses two extra arrays, and many people find it easier to check, at the price of slightly longer code.

9Conclusion

We found the largest rectangle by noticing that every rectangle is as tall as its lowest bar, so each bar has one rectangle that matters, stretched to the nearest lower bars on both sides. A stack of indexes with rising heights finds both limits when a bar is popped, and a pretend bar of height 0 empties the stack at the end. That is O(n) time and O(n) space, against O(n^2) for every range. The clue to remember is how far each element reaches before something smaller stops it.

What to say in the interviewAbout 80 seconds aloud

Open with

Let me confirm: every bar is one unit wide, heights can be zero, and an empty histogram gives zero. The brute force tries every range with a running minimum, which is n squared.

Then, if they want more

The observation is that every rectangle is as tall as its lowest bar, so for each bar only one rectangle matters, stretched to the nearest lower bar on each side. That is a nearest smaller element problem, so I use a monotonic stack of indexes whose heights rise.

When the current bar is lower than or equal to the top, the top bar cannot extend past here, so I pop it. Its right limit is i and its left limit is the new top, or minus one, so its area is height times i minus left minus one, and I keep the maximum. Then I push i.

One extra step at index n with height zero measures the bars left at the end. Each index is pushed and popped once, so it is O(n) time and O(n) space. On the example, the bar of height 2 at index 4 pops the 6 and then the 5, giving area 10.

About this answer

Last updated
14 November 2026
Written for
Java 21, using only java.util
Checked
The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
Where the question comes from
Public interview write-ups, reworded by Scrivio; counted 19 times in that collection. How it is counted
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Given bar heights of a histogram, find the area of the largest rectangle it contains.": https://scrivio-interview-library.netlify.app/data-structures/solutions/given-bar-heights-of-a-histogram-find-the-area-of-the-largest-re-9fb8d6/