15% off all plans & roadmaps Use code

See plans

Largest Rectangle in Histogram

Updated

TL;DR: Find the biggest rectangle that fits under a bar chart. A monotonic stack finds each bar's left and right limits once, giving O(n) time.

Problem

You are given an array of integers heights. Each value is the height of a histogram bar, and every bar has width 1. Return the area of the largest rectangle that fits inside the histogram.

Example 1

Input: heights = [2,1,5,6,2,3]
Output: 10
Explanation: The largest rectangle covers the bars of height 5 and 6. It is 2 wide and 5 tall, so its area is 10.

Example 2

Input: heights = [2,4]
Output: 4

Constraints

  • 1 <= heights.length <= 10^5
  • 0 <= heights[i] <= 10^4

Constraints that matter

  • n up to 10^5 rules out O(n^2) in the worst case. A sorted input makes the expand-from-each-bar method do about 5 * 10^9 steps, which is too slow.
  • Heights up to 10^4 and n up to 10^5 give a maximum area of 10^9. That fits in a signed 32-bit int (limit about 2.147 * 10^9), so no long is needed.
  • Heights can be 0. A zero bar splits the histogram, and it also works as a natural sentinel to flush the stack at the end.
  • n is at least 1, so you never handle an empty array, but a single bar must return its own height.

View on LeetCode

Hints

Hint 1

Every maximal rectangle has a shortest bar.

Hint 2

Treat each bar as the shortest bar of its rectangle.

Solution

Intuition

Every maximal rectangle has a shortest bar. If you know which bar is the shortest, the rectangle's height is fixed. Its width is the largest run of bars around that bar that are all at least as tall. So the problem becomes: for each bar, how far can it stretch left and right before it meets a strictly shorter bar?

Picture a line of people standing in order of height, where a shorter newcomer forces every taller person ahead to step out. The line is the stack, the newcomer is bar i, and each person who steps out gets their right limit set there.

That question is the nearest smaller element problem, and the pattern for it is a monotonic stack. Keep a stack of indices whose heights increase from bottom to top. When a new bar is shorter than the top, the top bar can never extend past the new bar, so the new bar is its right limit. The entry below it on the stack is its left limit, because everything between them was already popped for being taller.

This works because a bar only sits on the stack while no shorter bar has appeared to its right. Each pop settles exactly one bar's rectangle. Each index is pushed once and popped once, so the whole scan is linear.

A second signal is that brute force repeats the same boundary scans. Bar 3 and bar 4 in a tall plateau both walk over the same neighbours. The stack stores what earlier bars already learned, so later bars do not walk again.

Watch the pattern animation

Worked example

Input: heights = [6, 2, 5, 4, 5, 1, 6]
Output: 12
Explanation: The bars at indices 2, 3 and 4 have heights 5, 4 and 5. The shortest is 4 and the run is 3 wide, so the area is 4 * 3 = 12. The bar of height 2 spans indices 0 to 4 for only 10, and the bar of height 1 spans all 7 bars for only 7.

Approach 1: Brute force: expand from every bar

Treat each bar as the shortest bar of its rectangle. Walk left while the neighbour is at least as tall, then walk right the same way. The width is the length of that run, and the area is height times width.

This is correct because the best rectangle has some shortest bar, and for that bar the run you find is the widest rectangle of that height. It is also the version a beginner writes first.

Steps

  1. Set best = 0.
  2. For each index i, let h = heights[i].
  3. Move left leftward from i while the bar at left - 1 is at least h.
  4. Move right rightward from i while the bar at right + 1 is at least h.
  5. Compute the area h * (right - left + 1) and keep the larger of it and best.
  6. Return best after the loop.

Dry run

Trace on [6, 2, 5, 4, 5, 1, 6]. Each row shows the run found around bar i.

ihrun (left..right)widtharea
060..016
120..4510
252..215
342..4312
454..415
510..677
666..616

The largest area in the table is 12, from bar 3. That matches the expected output.

Complexity

TimeO(n^2)
SpaceO(1)

Here n is the number of bars. Each bar triggers two walks, and a walk can cover up to n bars, for example when the array is sorted or all values are equal. That gives n * n steps in the worst case. The code stores only a few integers, so extra space is constant.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def largestRectangleArea(self, heights: List[int]) -> int:
        n = len(heights)
        best = 0
        for i in range(n):
            h = heights[i]
            left = i
            while left > 0 and heights[left - 1] >= h:
                left -= 1
            right = i
            while right < n - 1 and heights[right + 1] >= h:
                right += 1
            best = max(best, h * (right - left + 1))
        return best

Approach 2: Two passes with a stack for smaller neighbours

What's slow: every bar re-walks neighbours that earlier bars already walked. In a rising staircase, bar 5 walks over bars 4, 3, 2 and 1 again, though bar 4 did the same moments before.

The insight that fixes it: finding the previous smaller bar and the next smaller bar for every index is a standard monotonic stack job. Build left[i] in a left-to-right pass and right[i] in a right-to-left pass. Then every width is right[i] - left[i] - 1, with no walking.

Pop while the top is at least as tall as the current bar. What remains on top is then strictly shorter, which is the boundary you want.

Steps

  1. Create left and right arrays of length n, and an empty stack of indices.
  2. Scan left to right. Pop while the top bar is at least as tall as heights[i].
  3. Set left[i] to the top of the stack, or -1 if the stack is empty. Push i.
  4. Clear the stack. Scan right to left with the same popping rule.
  5. Set right[i] to the top of the stack, or n if the stack is empty. Push i.
  6. For each i, compute heights[i] * (right[i] - left[i] - 1).
  7. Return the maximum of those areas.

Dry run

Trace on [6, 2, 5, 4, 5, 1, 6].

Left pass gives previous strictly smaller indices: left = [-1, -1, 1, 1, 3, -1, 5]. For example, at index 4 (height 5) the stack holds indices 1 and 3, and index 3 (height 4) is shorter, so left[4] = 3.

Right pass gives next strictly smaller indices: right = [1, 5, 3, 5, 5, 7, 7]. At index 3 (height 4) the next smaller bar is index 5 (height 1).

Widths right - left - 1 are [1, 5, 1, 3, 1, 7, 1]. Areas are [6, 10, 5, 12, 5, 7, 6]. The maximum is 12.

Complexity

TimeO(n)
SpaceO(n)

Here n is the number of bars. In each pass every index is pushed once and popped at most once, so each pass does at most 2n stack operations. The final loop is n steps. The two arrays and the stack each hold up to n integers, so space is O(n).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def largestRectangleArea(self, heights: List[int]) -> int:
        n = len(heights)
        left = [-1] * n
        right = [n] * n
        stack = []
        for i in range(n):
            while stack and heights[stack[-1]] >= heights[i]:
                stack.pop()
            left[i] = stack[-1] if stack else -1
            stack.append(i)
        stack = []
        for i in range(n - 1, -1, -1):
            while stack and heights[stack[-1]] >= heights[i]:
                stack.pop()
            right[i] = stack[-1] if stack else n
            stack.append(i)
        best = 0
        for i in range(n):
            best = max(best, heights[i] * (right[i] - left[i] - 1))
        return best
Largest Rectangle in Histogram pattern infographic for Largest Rectangle in Histogram

Solution pattern

Largest Rectangle in Histogram

Part of Stack Patterns

Approach 3: One-pass monotonic stackOptimalLargest Rectangle in Histogram

What's slow: the two-pass version is linear but builds two extra arrays and reads the input three times. Both boundaries of a bar are available at the moment it is popped, so you do not need to store them.

The insight that fixes it: keep one stack of indices with increasing heights. When bar i is shorter than the top, the top's right limit is i. The entry now under it is its left limit. Compute the area right then and discard the bar.

Append a virtual bar of height 0 at index n. It is shorter than every real bar, so it flushes the stack and removes any special end-of-loop code.

Steps

  1. Create an empty stack of indices and set best = 0.
  2. Loop i from 0 to n inclusive. Use cur = heights[i], or 0 when i == n.
  3. While the stack is non-empty and cur is less than the height at the top index, pop it and call its height h.
  4. Set the width to i if the stack is now empty. Otherwise use i - stack.top - 1.
  5. Update best with h * width.
  6. After the while loop, push i.
  7. Return best.

Dry run

Trace on [6, 2, 5, 4, 5, 1, 6], with cur = 0 at i = 7. Stack entries are indices.

icurpops (index, h, width, area)stack after pushbest
06none[0]0
12(0, 6, 1, 6)[1]6
25none[1, 2]6
34(2, 5, 1, 5)[1, 3]6
45none[1, 3, 4]6
51(4, 5, 1, 5), (3, 4, 3, 12), (1, 2, 5, 10)[5]12
66none[5, 6]12
70(6, 6, 1, 6), (5, 1, 7, 7)[7]12

At i = 5, popping index 3 leaves index 1 on top, so the width is 5 - 1 - 1 = 3 and the area is 4 * 3 = 12. Popping index 1 empties the stack, so its width is the full 5. The final answer is 12.

Complexity

TimeO(n)
SpaceO(n)

Here n is the number of bars. The for loop runs n + 1 times. Each index is pushed exactly once and popped at most once, so the while loop body runs at most n times in total across all iterations, giving O(n) time. The stack holds up to n indices when the heights strictly increase, so space is O(n).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def largestRectangleArea(self, heights: List[int]) -> int:
        n = len(heights)
        stack = []  # indices with increasing heights
        best = 0
        for i in range(n + 1):
            cur = heights[i] if i < n else 0  # height 0 flushes the stack
            while stack and cur < heights[stack[-1]]:
                h = heights[stack.pop()]
                # left limit is the new top, right limit is i
                width = i if not stack else i - stack[-1] - 1
                best = max(best, h * width)
            stack.append(i)
        return best

Common mistakes

  • Using width = i - stack[-1] after the pop. The new top is the left limit and is excluded from the rectangle, so the correct width is i - stack[-1] - 1.
  • Reading stack[-1] when the stack is empty after a pop. An empty stack means the popped bar was the shortest so far, so its width is i. Guard it with i if not stack else ....
  • Returning best right after the loop over range(n) with no flush. An increasing input like [1, 2, 3] never pops anything, so the answer stays 0. Loop to n with a height of 0, or drain the stack afterwards.
  • Storing heights on the stack and then trying to compute widths. Widths need positions, so push indices and look up heights[index] when you need the height.
  • Popping with cur <= heights[top] in the one-pass version and then miscalculating widths for equal bars. Strict < is the safe choice, and the earlier of two equal bars still gets the full width. In the two-pass version, pop on >= so the boundary is strictly smaller.
  • Computing the area only for the bar that triggers a push, not for every popped bar. Each pop settles one rectangle, so the area update must sit inside the while loop.

Edge cases

  • [5]: a single bar. The answer is 5, found when the sentinel at index 1 pops it with width 1.
  • [0] or [0, 0, 0]: all zeros. The answer is 0, and no pop ever produces a positive area.
  • [1, 2, 3, 4, 5]: strictly increasing. Nothing pops until the sentinel, which then pops 5, 4, 3, 2, 1 in turn. The best is 9, from height 3 with width 3.
  • [5, 4, 3, 2, 1]: strictly decreasing. Every new bar pops the previous one. The best is 9, from height 3 with width 3 once the sentinel flushes.
  • [3, 3, 3, 3]: all equal. The answer is 12, and the bottom bar of the stack gets the full width of 4.
  • [2, 0, 2]: a zero in the middle splits the histogram. The answer is 2, not 6.

Follow-ups interviewers ask

Can you solve it with divide and conquer or a segment tree?
Yes. Find the index of the minimum bar in the range. The best rectangle either uses that bar at full width, or lies entirely left of it, or entirely right of it. With a segment tree for range-minimum queries, each split costs O(log n), giving O(n log n) overall. Without one, scanning for the minimum gives O(n^2) on sorted input. The stack is simpler and linear.
How do you reuse this for the Maximal Rectangle problem on a binary matrix?
Process the matrix row by row. For each column keep a running height: add 1 if the cell is 1, reset to 0 if it is 0. Each row is then a histogram, and you run this exact algorithm on it. With r rows and c columns that costs O(r * c) time and O(c) space.
Can you do it in O(1) extra space?
Not with this approach, since the stack can hold n indices on a strictly increasing input. You can reuse the input array to store left bounds in place using a pointer-jumping trick, which avoids the stack. It makes the code fragile and is rarely expected. State that O(n) space is the standard answer and explain why the stack grows.

Largest Rectangle in Histogram FAQ

What is the time complexity of Largest Rectangle in Histogram?

The monotonic stack solution runs in O(n) time and O(n) space. Each index is pushed once and popped once, so the total stack work is at most 2n. The brute force that expands from each bar is O(n^2) in the worst case.

Why use a monotonic stack for Largest Rectangle in Histogram?

Each rectangle is limited by its shortest bar, so you need the nearest strictly shorter bar on each side of every index. A monotonic stack of increasing heights finds both in one pass. A bar is popped exactly when its right limit appears, and the entry beneath it is its left limit.

Why add a bar of height 0 at the end?

Bars that never meet a shorter bar to their right stay on the stack after the loop. A virtual bar of height 0 at index n is shorter than all of them. It pops every remaining bar through the same code path, so you need no second cleanup loop.

How do I compute the width when a bar is popped?

After popping, look at the new top of the stack. If the stack is empty, the width is i, because the bar reaches back to index 0. Otherwise the width is i - top - 1, which counts only the bars strictly between the left limit and the right limit.

Can Largest Rectangle in Histogram be solved in O(1) extra space?

Not in the standard solution. The stack can hold all n indices when heights strictly increase. Brute force uses O(1) space but needs O(n^2) time, which is too slow for n up to 10^5.

Does the order of equal heights matter in the stack?

No. With strict < popping, equal bars stay stacked and the earliest one later gets the full width on its pop. The later duplicate computes a smaller rectangle that the earlier one already covers, so the answer is unchanged.

Asked at

See which companies ask this — Pro

Practise it