Largest Rectangle in Histogram

Pattern: Monotonic stack

hard

The best rectangle is as tall as some bar and stretches from that bar's nearest shorter neighbour on the left to the nearest shorter on the right. A stack of rising bars finds both: a bar is popped by its right neighbour, and the bar under it is its left one.

The problem

Given bar heights of a histogram, each bar 1 wide, return the area of the largest rectangle inside it. [2, 1, 5, 6, 2, 3] gives 10 (the bars 5 and 6, height 5, width 2).

Think first

  • What height can the best rectangle have?
  • For a fixed bar as the shortest, how wide can the rectangle be?
  • Which structure finds the nearest shorter bars on both sides?

Hints

    Brute force, and why it fails

    For every pair of ends, find the minimum height: O(n²) with a running minimum.

    The key insight

    When a bar is popped, the bar beneath it is its nearest shorter on the left and the current bar is its nearest shorter on the right, so its whole rectangle is known at that moment.

    Dry run

    20 
    11i
    52 
    63 
    24 
    35 
    best2

    heights = [2, 1, 5, 6, 2, 3]. Push 0. Bar 1 pops bar 0: width 1, area 2.

    Step 1 of 4

    The plan

    for i from 0 to n (height 0 at i == n):
        while stack and heights[top] >= h:
            height = heights[pop]
            left = top or -1
            best = max(best, height * (i - left - 1))
        push i
    

    Complexity

    Time
    O(n)
    Space
    O(n)

    Each bar is pushed and popped once.

    Edge cases

    • One bar.
    • All equal: height × n.
    • A height-0 bar splits the histogram.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int largestRectangleArea(int[] heights) {
            int n = heights.length, best = 0;
            Deque<Integer> st = new ArrayDeque<>();         // bar indexes, heights increasing from bottom to top
            for (int i = 0; i <= n; i++) {
                int h = i == n ? 0 : heights[i];            // a 0 at the end flushes every bar
                while (!st.isEmpty() && heights[st.peek()] >= h) {
                    int height = heights[st.pop()];         // the popped bar is the shortest of its rectangle
                    int left = st.isEmpty() ? -1 : st.peek();   // the rectangle spans left + 1 .. i - 1
                    best = Math.max(best, height * (i - left - 1));
                }
                st.push(i);
            }
            return best;
        }
    }

    C++

    class Solution {
    public:
        int largestRectangleArea(vector<int>& heights) {
            int n = static_cast<int>(heights.size()), best = 0;
            stack<int> st;                                  // bar indexes, heights increasing from bottom to top
            for (int i = 0; i <= n; i++) {
                int h = i == n ? 0 : heights[i];            // a 0 at the end flushes every bar
                while (!st.empty() && heights[st.top()] >= h) {
                    int height = heights[st.top()];         // the popped bar is the shortest of its rectangle
                    st.pop();
                    int left = st.empty() ? -1 : st.top();  // the rectangle spans left + 1 .. i - 1
                    best = max(best, height * (i - left - 1));
                }
                st.push(i);
            }
            return best;
        }
    };

    Python

    class Solution:
        def largestRectangleArea(self, heights: list[int]) -> int:
            n, best, st = len(heights), 0, []       # st: bar indexes, heights increasing from bottom to top
            for i in range(n + 1):
                h = 0 if i == n else heights[i]     # a 0 at the end flushes every bar
                while st and heights[st[-1]] >= h:
                    height = heights[st.pop()]      # the popped bar is the shortest of its rectangle
                    left = st[-1] if st else -1     # the rectangle spans left + 1 .. i - 1
                    best = max(best, height * (i - left - 1))
                st.append(i)
            return best

    Common mistakes

    • Forgetting the final flush with height 0.
    • Computing the width as i - popped instead of i - left - 1.

    Similar problems