Largest Rectangle in Histogram

Monotonic increasing stack — at every pop, the popped bar's rectangle spans from previous stack top to current index.

Hard
Time O(n) Space O(n)
LeetCode
3 min read
monotonic-stack array

Problem#

Given bar heights, return the area of the largest axis-aligned rectangle entirely inside the histogram.

Examples#

  • [2,1,5,6,2,3]10.
  • [2,4]4.

Constraints#

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

Approach#

Monotonic increasing stack of indices. For each new bar, pop bars taller than it; for each popped bar, its rectangle’s width is i - (stack.top() after pop) - 1. Append a sentinel 0 to flush remaining bars.

Solution#

Largest Rectangle in Histogram
class Solution {
public:
int largestRectangleArea(vector<int>& h) {
h.push_back(0);
stack<int> st;
int best = 0;
for (int i = 0; i < (int)h.size(); ++i) {
while (!st.empty() && h[st.top()] > h[i]) {
int top = st.top(); st.pop();
int width = st.empty() ? i : (i - st.top() - 1);
best = max(best, h[top] * width);
}
st.push(i);
}
h.pop_back();
return best;
}
};

Editorial#

The stack stores increasing-height bar indices. When a shorter bar arrives, every taller bar in the stack has found its right boundary (the new bar) — and its left boundary is the previous stack element after popping. Each bar is pushed and popped at most once: O(n).

Complexity#

  • Time: O(n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.