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

Edge cases to test

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 best

C++

#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