Tech Interview RoomStudy guides

Stack & Queue

Largest rectangle in a histogram. Compare brute force, divide and conquer, and the monotonic stack.

Advanced · 2 min read · Lesson 4 of 4 in Stack & Queue

Problem

Bar heights [2, 1, 5, 6, 2, 3] (width 1 each) → largest rectangle area 10 (bars 5 and 6, height 5).

Pattern

Monotonic increasing stack: for each bar, the rectangle using it as the shortest bar extends left to the previous smaller bar and right to the next smaller bar. The stack finds both boundaries in one pass.

Approach 1: Expand from every bar (feasible, O(n²))

java
class HistogramBrute {
    static int largest(int[] h) {
        int best = 0;
        for (int i = 0; i < h.length; i++) {
            int left = i, right = i;
            while (left > 0 && h[left - 1] >= h[i]) left--;
            while (right < h.length - 1 && h[right + 1] >= h[i]) right++;
            best = Math.max(best, h[i] * (right - left + 1));
        }
        return best;
    }
}

Approach 2: Divide and conquer on the minimum bar (O(n log n) average, O(n²) worst)

The best rectangle either uses the minimum bar across the whole range, or lies entirely left or right of it.

java
class HistogramDivide {
    static int largest(int[] h) { return solve(h, 0, h.length - 1); }
    private static int solve(int[] h, int lo, int hi) {
        if (lo > hi) return 0;
        int min = lo;
        for (int i = lo; i <= hi; i++) if (h[i] < h[min]) min = i;
        return Math.max(h[min] * (hi - lo + 1), Math.max(solve(h, lo, min - 1), solve(h, min + 1, hi)));
    }
}

Approach 3: Monotonic stack (O(n)) — optimal

When the current bar is lower than the stack top, the top bar's rectangle ends here; its left boundary is the new stack top after popping. A sentinel height 0 at the end flushes the stack.

java
import java.util.ArrayDeque;
import java.util.Deque;

class HistogramStack {
    static int largest(int[] h) {
        Deque<Integer> stack = new ArrayDeque<>();
        int best = 0;
        for (int i = 0; i <= h.length; i++) {
            int current = i == h.length ? 0 : h[i];
            while (!stack.isEmpty() && h[stack.peek()] > current) {
                int height = h[stack.pop()];
                int leftBoundary = stack.isEmpty() ? -1 : stack.peek();
                best = Math.max(best, height * (i - leftBoundary - 1));
            }
            stack.push(i);
        }
        return best;
    }
}

class HistogramDemo {
    public static void main(String[] args) {
        int[] h = {2, 1, 5, 6, 2, 3};
        System.out.println(HistogramBrute.largest(h) + " " + HistogramDivide.largest(h) + " " + HistogramStack.largest(h));   // 10 10 10
    }
}

Feasible → optimal

O(n²) expansion → O(n log n) average with divide and conquer → O(n) with a monotonic stack.

Follow-up questions interviewers ask

Try answering each one before you open it.

Related (same pattern): maximal rectangle of 1s in a binary matrix.

Treat each row as the base of a histogram whose heights are the counts of consecutive 1s above, then run the histogram algorithm per row. O(rows × cols).

Related (same pattern): sum of subarray minimums.

For each element, use monotonic stacks to find how far it extends left and right as the minimum (previous less and next less-or-equal); it contributes value × leftCount × rightCount. O(n).