Algo-Sim › Stacks & Monotonic Stack
Largest Rectangle in Histogram
Hard · Stacks & Monotonic Stack · step through it in Java, Python and C++ on your own input
Bars of width 1 stand side by side. Return the area of the largest rectangle that fits inside the histogram.
Problem
A histogram has bars of width 1 with heights heights[i], placed side by side. Return the area of the largest axis-aligned rectangle that fits entirely inside the bars.
Constraints
- 1 ≤ heights.length ≤ 10⁵
- 0 ≤ heights[i] ≤ 10⁴
- Trying every pair of edges is O(n²)
Edge cases to test
- Strictly increasing bars (all popped at the end)
- All bars equal
- A zero-height bar
Follow-up questions
- Why push a sentinel 0 at the end?
- It pops every bar left on the stack, so the final cleanup is the same code as the main loop.
- What does each pop compute?
- The popped bar is the shortest in the span between the new top and the current index, which is the widest rectangle of that height.
Solution
Java
public int largestRectangleArea(int[] heights) {
int n = heights.length, best = 0;
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i <= n; i++) {
int h = (i == n) ? 0 : heights[i];
while (!stack.isEmpty() && heights[stack.peek()] >= h) {
int height = heights[stack.pop()];
int left = stack.isEmpty() ? -1 : stack.peek();
best = Math.max(best, height * (i - left - 1));
}
stack.push(i);
}
return best;
}Python
def largest_rectangle_area(heights):
n, best = len(heights), 0
stack = []
for i in range(n + 1):
h = 0 if i == n else heights[i]
while stack and heights[stack[-1]] >= h:
height = heights[stack.pop()]
left = stack[-1] if stack else -1
best = max(best, height * (i - left - 1))
stack.append(i)
return bestC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int largestRectangleArea(vector<int> &heights) {
int n = int(heights.size()), best = 0;
deque<int> stack = {};
for (int i = 0; i <= n; i++) {
int h = (i == n) ? 0 : heights[i];
while (!stack.empty() && heights[stack.back()] >= h) {
int height = heights[stack.back()];
stack.pop_back();
int left = stack.empty() ? -1 : stack.back();
best = std::max(best, height * (i - left - 1));
}
stack.push_back(i);
}
return best;
}
};
More Stacks & Monotonic Stack problems
- Valid Parentheses (Easy)
- Implement Queue using Stacks (Easy)
- Evaluate Reverse Polish Notation (Medium)
- Basic Calculator II (Medium)
- Basic Calculator (Hard)
- Decode String (Medium)
- Asteroid Collision (Medium)
- Next Greater Element (Easy)
- Daily Temperatures (Medium)
- Remove K Digits (Medium)
- Online Stock Span (Medium)
- Car Fleet (Medium)
- Maximal Rectangle (Hard)
- Sliding Window Maximum (Hard)