15% off all plans & roadmaps Use code
See plansLargest Rectangle in Histogram
- LeetCode 84
- Hard
- Stack Patterns
- 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^50 <= heights[i] <= 10^4
Constraints that matter
nup 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
nup 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 nolongis 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.
nis at least 1, so you never handle an empty array, but a single bar must return its own height.
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.
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
- Set
best = 0. - For each index
i, leth = heights[i]. - Move
leftleftward fromiwhile the bar atleft - 1is at leasth. - Move
rightrightward fromiwhile the bar atright + 1is at leasth. - Compute the area
h * (right - left + 1)and keep the larger of it andbest. - Return
bestafter the loop.
Dry run
Trace on [6, 2, 5, 4, 5, 1, 6]. Each row shows the run found around bar i.
| i | h | run (left..right) | width | area |
|---|---|---|---|---|
| 0 | 6 | 0..0 | 1 | 6 |
| 1 | 2 | 0..4 | 5 | 10 |
| 2 | 5 | 2..2 | 1 | 5 |
| 3 | 4 | 2..4 | 3 | 12 |
| 4 | 5 | 4..4 | 1 | 5 |
| 5 | 1 | 0..6 | 7 | 7 |
| 6 | 6 | 6..6 | 1 | 6 |
The largest area in the table is 12, from bar 3. That matches the expected output.
Complexity
| Time | O(n^2) |
|---|---|
| Space | O(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 bestJavaTested in our runner
import java.util.*;
class Solution {
public int largestRectangleArea(int[] heights) {
int n = heights.length;
int best = 0;
for (int i = 0; i < n; i++) {
int h = heights[i];
int left = i;
while (left > 0 && heights[left - 1] >= h) left--;
int right = i;
while (right < n - 1 && heights[right + 1] >= h) right++;
best = Math.max(best, h * (right - left + 1));
}
return best;
}
}C++Tested in our runner
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int n = heights.size();
int best = 0;
for (int i = 0; i < n; i++) {
int h = heights[i];
int left = i;
while (left > 0 && heights[left - 1] >= h) left--;
int right = i;
while (right < n - 1 && heights[right + 1] >= h) right++;
best = max(best, h * (right - left + 1));
}
return best;
}
};JavaScriptTested in our runner
/**
* @param {number[]} heights
* @return {number}
*/
var largestRectangleArea = function(heights) {
const n = heights.length;
let best = 0;
for (let i = 0; i < n; i++) {
const h = heights[i];
let left = i;
while (left > 0 && heights[left - 1] >= h) left--;
let right = i;
while (right < n - 1 && heights[right + 1] >= h) right++;
best = Math.max(best, h * (right - left + 1));
}
return best;
};GoTested in our runner
func largestRectangleArea(heights []int) int {
n := len(heights)
best := 0
for i := 0; i < n; i++ {
h := heights[i]
left := i
for left > 0 && heights[left-1] >= h {
left--
}
right := i
for right < n-1 && heights[right+1] >= h {
right++
}
if area := h * (right - left + 1); area > best {
best = area
}
}
return best
}C#Tested in our runner
public class Solution {
public int largestRectangleArea(int[] heights) {
int n = heights.Length;
int best = 0;
for (int i = 0; i < n; i++) {
int h = heights[i];
int left = i;
while (left > 0 && heights[left - 1] >= h) left--;
int right = i;
while (right < n - 1 && heights[right + 1] >= h) right++;
best = Math.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
- Create
leftandrightarrays of lengthn, and an empty stack of indices. - Scan left to right. Pop while the top bar is at least as tall as
heights[i]. - Set
left[i]to the top of the stack, or-1if the stack is empty. Pushi. - Clear the stack. Scan right to left with the same popping rule.
- Set
right[i]to the top of the stack, ornif the stack is empty. Pushi. - For each
i, computeheights[i] * (right[i] - left[i] - 1). - 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
| Time | O(n) |
|---|---|
| Space | O(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 bestJavaTested in our runner
import java.util.*;
class Solution {
public int largestRectangleArea(int[] heights) {
int n = heights.length;
int[] left = new int[n];
int[] right = new int[n];
int[] stack = new int[n];
int top = 0;
for (int i = 0; i < n; i++) {
while (top > 0 && heights[stack[top - 1]] >= heights[i]) top--;
left[i] = top == 0 ? -1 : stack[top - 1];
stack[top++] = i;
}
top = 0;
for (int i = n - 1; i >= 0; i--) {
while (top > 0 && heights[stack[top - 1]] >= heights[i]) top--;
right[i] = top == 0 ? n : stack[top - 1];
stack[top++] = i;
}
int best = 0;
for (int i = 0; i < n; i++) {
best = Math.max(best, heights[i] * (right[i] - left[i] - 1));
}
return best;
}
}C++Tested in our runner
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int n = heights.size();
vector<int> left(n), right(n), stack;
for (int i = 0; i < n; i++) {
while (!stack.empty() && heights[stack.back()] >= heights[i]) stack.pop_back();
left[i] = stack.empty() ? -1 : stack.back();
stack.push_back(i);
}
stack.clear();
for (int i = n - 1; i >= 0; i--) {
while (!stack.empty() && heights[stack.back()] >= heights[i]) stack.pop_back();
right[i] = stack.empty() ? n : stack.back();
stack.push_back(i);
}
int best = 0;
for (int i = 0; i < n; i++) {
best = max(best, heights[i] * (right[i] - left[i] - 1));
}
return best;
}
};JavaScriptTested in our runner
/**
* @param {number[]} heights
* @return {number}
*/
var largestRectangleArea = function(heights) {
const n = heights.length;
const left = new Array(n).fill(-1);
const right = new Array(n).fill(n);
let stack = [];
for (let i = 0; i < n; i++) {
while (stack.length && heights[stack[stack.length - 1]] >= heights[i]) stack.pop();
left[i] = stack.length ? stack[stack.length - 1] : -1;
stack.push(i);
}
stack = [];
for (let i = n - 1; i >= 0; i--) {
while (stack.length && heights[stack[stack.length - 1]] >= heights[i]) stack.pop();
right[i] = stack.length ? stack[stack.length - 1] : n;
stack.push(i);
}
let best = 0;
for (let i = 0; i < n; i++) {
best = Math.max(best, heights[i] * (right[i] - left[i] - 1));
}
return best;
};GoTested in our runner
func largestRectangleArea(heights []int) int {
n := len(heights)
left := make([]int, n)
right := make([]int, n)
stack := make([]int, 0, n)
for i := 0; i < n; i++ {
for len(stack) > 0 && heights[stack[len(stack)-1]] >= heights[i] {
stack = stack[:len(stack)-1]
}
if len(stack) == 0 {
left[i] = -1
} else {
left[i] = stack[len(stack)-1]
}
stack = append(stack, i)
}
stack = stack[:0]
for i := n - 1; i >= 0; i-- {
for len(stack) > 0 && heights[stack[len(stack)-1]] >= heights[i] {
stack = stack[:len(stack)-1]
}
if len(stack) == 0 {
right[i] = n
} else {
right[i] = stack[len(stack)-1]
}
stack = append(stack, i)
}
best := 0
for i := 0; i < n; i++ {
if area := heights[i] * (right[i] - left[i] - 1); area > best {
best = area
}
}
return best
}C#Tested in our runner
public class Solution {
public int largestRectangleArea(int[] heights) {
int n = heights.Length;
int[] left = new int[n];
int[] right = new int[n];
int[] stack = new int[n];
int top = 0;
for (int i = 0; i < n; i++) {
while (top > 0 && heights[stack[top - 1]] >= heights[i]) top--;
left[i] = top == 0 ? -1 : stack[top - 1];
stack[top++] = i;
}
top = 0;
for (int i = n - 1; i >= 0; i--) {
while (top > 0 && heights[stack[top - 1]] >= heights[i]) top--;
right[i] = top == 0 ? n : stack[top - 1];
stack[top++] = i;
}
int best = 0;
for (int i = 0; i < n; i++) {
best = Math.Max(best, heights[i] * (right[i] - left[i] - 1));
}
return best;
}
}
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
- Create an empty stack of indices and set
best = 0. - Loop
ifrom 0 toninclusive. Usecur = heights[i], or0wheni == n. - While the stack is non-empty and
curis less than the height at the top index, pop it and call its heighth. - Set the width to
iif the stack is now empty. Otherwise usei - stack.top - 1. - Update
bestwithh * width. - After the while loop, push
i. - Return
best.
Dry run
Trace on [6, 2, 5, 4, 5, 1, 6], with cur = 0 at i = 7. Stack entries are indices.
| i | cur | pops (index, h, width, area) | stack after push | best |
|---|---|---|---|---|
| 0 | 6 | none | [0] | 0 |
| 1 | 2 | (0, 6, 1, 6) | [1] | 6 |
| 2 | 5 | none | [1, 2] | 6 |
| 3 | 4 | (2, 5, 1, 5) | [1, 3] | 6 |
| 4 | 5 | none | [1, 3, 4] | 6 |
| 5 | 1 | (4, 5, 1, 5), (3, 4, 3, 12), (1, 2, 5, 10) | [5] | 12 |
| 6 | 6 | none | [5, 6] | 12 |
| 7 | 0 | (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
| Time | O(n) |
|---|---|
| Space | O(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 bestJavaTested in our runner
import java.util.*;
class Solution {
public int largestRectangleArea(int[] heights) {
int n = heights.length;
int[] stack = new int[n + 1];
int top = 0;
int best = 0;
for (int i = 0; i <= n; i++) {
int cur = i == n ? 0 : heights[i];
while (top > 0 && cur < heights[stack[top - 1]]) {
int h = heights[stack[--top]];
int width = top == 0 ? i : i - stack[top - 1] - 1;
best = Math.max(best, h * width);
}
stack[top++] = i;
}
return best;
}
}C++Tested in our runner
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int n = heights.size();
vector<int> stack;
int best = 0;
for (int i = 0; i <= n; i++) {
int cur = i == n ? 0 : heights[i];
while (!stack.empty() && cur < heights[stack.back()]) {
int h = heights[stack.back()];
stack.pop_back();
int width = stack.empty() ? i : i - stack.back() - 1;
best = max(best, h * width);
}
stack.push_back(i);
}
return best;
}
};JavaScriptTested in our runner
/**
* @param {number[]} heights
* @return {number}
*/
var largestRectangleArea = function(heights) {
const n = heights.length;
const stack = [];
let best = 0;
for (let i = 0; i <= n; i++) {
const cur = i === n ? 0 : heights[i];
while (stack.length && cur < heights[stack[stack.length - 1]]) {
const h = heights[stack.pop()];
const width = stack.length === 0 ? i : i - stack[stack.length - 1] - 1;
best = Math.max(best, h * width);
}
stack.push(i);
}
return best;
};GoTested in our runner
func largestRectangleArea(heights []int) int {
n := len(heights)
stack := make([]int, 0, n+1)
best := 0
for i := 0; i <= n; i++ {
cur := 0
if i < n {
cur = heights[i]
}
for len(stack) > 0 && cur < heights[stack[len(stack)-1]] {
h := heights[stack[len(stack)-1]]
stack = stack[:len(stack)-1]
width := i
if len(stack) > 0 {
width = i - stack[len(stack)-1] - 1
}
if h*width > best {
best = h * width
}
}
stack = append(stack, i)
}
return best
}C#Tested in our runner
public class Solution {
public int largestRectangleArea(int[] heights) {
int n = heights.Length;
int[] stack = new int[n + 1];
int top = 0;
int best = 0;
for (int i = 0; i <= n; i++) {
int cur = i == n ? 0 : heights[i];
while (top > 0 && cur < heights[stack[top - 1]]) {
int h = heights[stack[--top]];
int width = top == 0 ? i : i - stack[top - 1] - 1;
best = Math.Max(best, h * width);
}
stack[top++] = 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 isi - 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 isi. Guard it withi if not stack else .... - Returning
bestright after the loop overrange(n)with no flush. An increasing input like[1, 2, 3]never pops anything, so the answer stays 0. Loop tonwith 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
whileloop.
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
Related problems
- Maximal Rectangle · same technique: Largest Rectangle in Histogram
- Reconstruct Itinerary · same pattern: Stack Patterns
- Maximum Frequency Stack · same pattern: Stack Patterns
- Basic Calculator · same pattern: Stack Patterns
- Longest Valid Parentheses · same pattern: Stack Patterns
- Basic Calculator III · same pattern: Stack Patterns
- Evaluate Reverse Polish Notation · same pattern: Stack Patterns
- Min Stack · same pattern: Stack Patterns
- Daily Temperatures · same pattern: Stack Patterns
- Car Fleet · same pattern: Stack Patterns