DSA stack learning path Level 3 This level · 2 of 2
Hard dsa stack

Largest Rectangle in Histogram

The 30 second answer

The largest rectangle that uses bar i as its shortest bar extends left and right until a strictly shorter bar. A monotonic increasing stack of indices tells me those bounds: when a shorter bar arrives, the popped bar's right edge is the new index and its left edge is the new top. A sentinel of height 0 at the end flushes the stack. Each bar is pushed and popped once.

Could you say this in an interview?

Problem Given an array of non-negative bar heights of width 1, return the area of the largest rectangle that can be formed in the histogram. Original: LeetCode 84: Largest Rectangle in Histogram. HackerRank Largest Rectangle is the same problem.

Understanding the prompt A rectangle is made of contiguous bars and is limited by the shortest bar inside it. It is enough, and easier, to consider for every bar the widest rectangle in which that bar is a shortest bar, then take the maximum area.

Pattern recognition A monotonic increasing stack that finds, for each index, the nearest smaller height on the left and on the right.

Brute force For every pair of ends, take the min height times the width: O(n²).

Optimal Walk i from 0 to n, treating a virtual height of 0 at index n so the stack is flushed. Keep a stack of increasing heights, storing indices. While the current height is less than the height at the top, pop: that popped bar ends at i, its left boundary is the new top (or −1 if the stack is empty), and the area is height * (i − left − 1). Then push i. The virtual 0 lets every leftover bar compute its area against the right end.

Alternatives Two explicit nearest-smaller arrays, one from the left and one from the right, are the same algorithm split into two passes. They are easier to prove and use slightly more code.

Java solution

import java.util.ArrayDeque;

public class LargestRectangleInHistogram {
    static int largestRectangleArea(int[] heights) {
        var st = new ArrayDeque<Integer>(); // increasing heights, store indices
        int best = 0, n = heights.length;
        for (int i = 0; i <= n; i++) {
            int h = i == n ? 0 : heights[i];
            while (!st.isEmpty() && h < heights[st.peek()]) {
                int height = heights[st.pop()];
                int left = st.isEmpty() ? -1 : st.peek();
                best = Math.max(best, height * (i - left - 1));
            }
            st.push(i);
        }
        return best;
    }

    public static void main(String[] args) {
        System.out.println(largestRectangleArea(new int[] {2, 1, 5, 6, 2, 3})); // 10
        System.out.println(largestRectangleArea(new int[] {2, 4}));             // 4
        System.out.println(largestRectangleArea(new int[] {2, 1, 2}));          // 3
    }
}

Complexity O(n) time, each index pushed and popped at most once. O(n) extra space for the stack.

Edge cases

  • Official samples: [2,1,5,6,2,3] returns 10, from the rectangle of height 2 and width 5 starting at the bar of height 5; [2,4] returns 4.
  • [2,1,2] returns 3, from the full width at height 1, which beats either single bar of height 2.

Follow-ups

  • Trapping Rain Water can also be solved with a monotonic stack, but two pointers are enough there.
  • Maximal Rectangle in a binary matrix reduces each row to a histogram and calls this routine.

Tests [2,1,5,6,2,3] returns 10. [2,4] returns 4. [2,1,2] returns 3.

How to say it in the interview "For each bar I want the widest rectangle in which it is a shortest bar. An increasing stack of indices gives me the nearest smaller bar on the left and on the right the moment a shorter bar arrives. A zero-height sentinel at the end flushes the stack. Linear time."

Sources (2)
  1. LeetCode 84: Largest Rectangle in Histogramleetcode.com
  2. HackerRank: Largest Rectanglehackerrank.com
Previous
Next