Largest Rectangle in Histogram (LeetCode 84): Solution and Explanation
A histogram is given as a list of bar heights, each bar one unit wide. Find the area of the largest rectangle that fits entirely inside the bars.
Watch it run step by step
Try your own input and write the code →Intuition
Every candidate rectangle is limited by its shortest bar. That suggests a brute force: for every pair of left and right edges, take the minimum height between them and multiply by the width. Done naively that is O(n³), and with a running minimum it is O(n²), still too slow for 100,000 bars.
Turn it around and ask, for each bar, what is the widest rectangle that uses this bar's full height? It extends left until it hits a shorter bar and right until it hits a shorter bar. If you knew, for every bar, where those shorter bars are, the answer would be the best height × width over all bars.
A monotonic increasing stack finds those boundaries in one pass. Keep bars on the stack in increasing height order. When a new bar is shorter than the top of the stack, the top bar can no longer extend to the right, because the new bar blocks it. So you pop it and compute its rectangle: its height times the distance from where it started to the current index. Its left boundary is already known, since everything below it on the stack is shorter.
The reference code adds one clever touch. When the new bar pops taller bars, it inherits the start index of the last bar it popped, because the new, shorter bar can extend left over all of them. After the pass, any bars left on the stack were never blocked on the right, so they extend all the way to the end of the histogram.
Approach: Monotonic increasing stack
- Set
maxArea = 0and an emptystackof (start index, height) pairs. - For each bar
iwith heighth, setstart = i. - While the top of the stack is taller than
h, pop(index, height), updatemaxAreawithheight * (i - index), and setstart = index. - Push
(start, h), so the current bar records how far left it can extend. - After the loop, for every remaining
(i, h)on the stack, updatemaxAreawithh * (len(heights) - i). - Return
maxArea.
Step-by-step example
heights = [2,1,5,6,2,3]
- i = 0, h = 2: push (0, 2). i = 1, h = 1: pop (0, 2) for area 2 × 1 = 2, then push (0, 1) using the inherited start 0.
- i = 2, h = 5: push (2, 5). i = 3, h = 6: push (3, 6). The stack is (0,1), (2,5), (3,6).
- i = 4, h = 2: pop (3, 6) for area 6 × 1 = 6, then pop (2, 5) for area 5 × 2 = 10.
maxAreais now 10. Push (2, 2). - i = 5, h = 3: push (5, 3). The stack is (0,1), (2,2), (5,3).
- Final sweep with length 6: (0,1) gives 1 × 6 = 6, (2,2) gives 2 × 4 = 8, (5,3) gives 3 × 1 = 3. None beats 10.
- The answer is 10, the rectangle of height 5 spanning the bars at indices 2 and 3.
Code: Python, Java, C++
1class Solution:
2 def largestRectangleArea(self, heights: List[int]) -> int:
3 maxArea = 0
4 stack = [] # pair: (index, height)
5
6 for i, h in enumerate(heights):
7 start = i
8 while stack and stack[-1][1] > h:
9 index, height = stack.pop()
10 maxArea = max(maxArea, height * (i - index))
11 start = index
12 stack.append((start, h))
13
14 for i, h in stack:
15 maxArea = max(maxArea, h * (len(heights) - i))
16 return maxArea1class Solution {
2 public int largestRectangleArea(int[] heights) {
3 int maxArea = 0;
4 Stack<int[]> stack = new Stack<>(); // index, height
5
6 for (int i = 0; i < heights.length; i++) {
7 int start = i;
8 while (!stack.isEmpty() && stack.peek()[1] > heights[i]) {
9 int[] pair = stack.pop();
10 int index = pair[0];
11 int height = pair[1];
12 maxArea = Math.max(maxArea, height * (i - index));
13 start = index;
14 }
15 stack.push(new int[]{start, heights[i]});
16 }
17
18 for (int[] pair : stack) {
19 maxArea = Math.max(maxArea, pair[1] * (heights.length - pair[0]));
20 }
21 return maxArea;
22 }
23}1class Solution {
2public:
3 int largestRectangleArea(vector<int>& heights) {
4 int maxArea = 0;
5 vector<pair<int, int>> stack; // index, height
6
7 for (int i = 0; i < heights.size(); ++i) {
8 int start = i;
9 while (!stack.empty() && stack.back().second > heights[i]) {
10 pair<int, int> top = stack.back();
11 stack.pop_back();
12 int index = top.first;
13 int height = top.second;
14 maxArea = max(maxArea, height * (i - index));
15 start = index;
16 }
17 stack.push_back({start, heights[i]});
18 }
19
20 for (auto& p : stack) {
21 maxArea = max(maxArea, p.second * (int)(heights.size() - p.first));
22 }
23 return maxArea;
24 }
25};Time and space complexity
O(n)
Each bar is pushed once and popped at most once, and the final sweep touches each remaining bar once.
O(n)
For a strictly increasing histogram, every bar stays on the stack until the end.
Other approaches
Expand from every bar (time O(n²), space O(1))
For each bar, walk left and right while neighbors are at least as tall, then compute the area. It is easy to reason about but quadratic on inputs like a sorted histogram.
Precomputed nearest smaller arrays (time O(n), space O(n))
Use two monotonic stack passes to build left[i] and right[i], the nearest shorter bars on each side, then compute heights[i] × (right[i] - left[i] - 1) for every bar. It separates the boundary finding from the area step, which some people find easier to debug.
Common mistakes
- Pushing the current index instead of the inherited
start. The shorter bar can extend left over every taller bar it popped, and losing that gives areas that are too small. - Forgetting the final sweep over the stack, which misses rectangles that reach the right edge, such as in a strictly increasing histogram.
- Using
i - index - 1as the width. Because the stack stores each bar's start index, the width of a popped bar is exactlyi - index. - Popping on
>=and then mishandling equal heights. Equal bars are harmless to keep, and the reference code only pops strictly taller ones.
Frequently asked questions
Why does a monotonic stack solve Largest Rectangle in Histogram?
Each bar's best rectangle is bounded by the nearest shorter bar on each side. An increasing stack discovers the right boundary at the moment a bar is popped, and the left boundary is whatever start index the bar carries.
What is the time complexity?
It is O(n). Every bar is pushed and popped at most once, so the total number of stack operations is linear.
How does this relate to Maximal Rectangle?
Maximal Rectangle in a binary matrix treats each row as the base of a histogram of consecutive ones and runs this algorithm on every row. That gives an O(rows × cols) solution.
Why do we process the remaining stack at the end?
Bars still on the stack never met a shorter bar to their right, so their rectangles extend to the last index. Their width is the total length minus their start index.