Largest Rectangle in Histogram
Hard
Topics
Given an array heights of bar heights (each width 1), return the area of the largest rectangle that fits in the histogram.
Example 1
Bars are the histogram heights; the answer is the largest axis-aligned rectangle that fits entirely under this outline.
Input: heights = [2,1,5,6,2,3] Output: 10
Example 2
Input: heights = [2,4] Output: 4
Constraints
- 1 <= heights.length <= 10^5
- 0 <= heights[i] <= 10^4
Editorial — intuition, approach, complexity and pitfalls
Intuition
For each bar the widest rectangle of its height extends until a shorter bar on either side. A monotonic increasing stack lets you find, at the moment a bar is popped, exactly that left and right boundary.
Approach
- Keep a stack of indices with increasing heights.
- When the current bar is shorter than the stack top, pop it; its height times the width between the new top and current index is a candidate area.
- Use a trailing 0-height sentinel to flush the stack.
Dry Run
nums = [2, 1, 5, 6, 2, 3], with a 0 appended as a sentinel so the stack always drains
i=0 h=2 push stack=[0]
i=1 h=1 pop 0: height 2, width 1 best=2 push stack=[1]
i=2 h=5 push stack=[1, 2]
i=3 h=6 push stack=[1, 2, 3]
i=4 h=2 pop 3: height 6, width 1 best=6
pop 2: height 5, width 2 best=10 push stack=[1, 4]
i=5 h=3 push stack=[1, 4, 5]
i=6 h=0 pop 5: height 3, width 1
pop 4: height 2, width 4
pop 1: height 1, width 6 stack=[]
answer 10 (heights 5 and 6, two bars wide)Complexity
- Time — O(n): each bar is pushed and popped once.
- Space — O(n): the stack.
Common Pitfalls
- Compute width from the index below the popped bar, not the popped index itself.
Full Solution — all languages
class Solution:
def largestRectangleArea(self, nums):
stack = []
best = 0
heights = nums + [0]
for i, h in enumerate(heights):
while stack and heights[stack[-1]] >= h:
height = heights[stack.pop()]
width = i if not stack else i - stack[-1] - 1
if height * width > best:
best = height * width
stack.append(i)
return bestimport java.util.*;
class Solution {
public int largestRectangleArea(int[] nums) {
int n = nums.length;
int[] heights = new int[n + 1];
for (int i = 0; i < n; i++) heights[i] = nums[i];
heights[n] = 0;
Deque<Integer> stack = new ArrayDeque<>();
int best = 0;
for (int i = 0; i <= n; i++) {
while (!stack.isEmpty() && heights[stack.peek()] >= heights[i]) {
int height = heights[stack.pop()];
int width = stack.isEmpty() ? i : i - stack.peek() - 1;
if (height * width > best) best = height * width;
}
stack.push(i);
}
return best;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int largestRectangleArea(vector<int>& nums) {
vector<int> heights = nums;
heights.push_back(0);
vector<int> stack;
int best = 0;
for (int i = 0; i < (int)heights.size(); i++) {
while (!stack.empty() && heights[stack.back()] >= heights[i]) {
int height = heights[stack.back()];
stack.pop_back();
int width = stack.empty() ? i : i - stack.back() - 1;
if (height * width > best) best = height * width;
}
stack.push_back(i);
}
return best;
}
};/**
* @param {number[]} nums
* @return {number}
*/ var largestRectangleArea = function(nums) {
const stack = [];
let best = 0;
const heights = nums.concat([0]);
for (let i = 0; i < heights.length; i++) {
while (stack.length && heights[stack[stack.length - 1]] >= heights[i]) {
const height = heights[stack.pop()];
const width = stack.length === 0 ? i : i - stack[stack.length - 1] - 1;
if (height * width > best) best = height * width;
}
stack.push(i);
}
return best;
};