Largest Rectangle in Histogram - Monotonic Stack Pattern

Largest Rectangle in Histogram in Java using the Monotonic Stack pattern: problem statement, approach, template, complexity, and interview tips.

Largest Rectangle in Histogram

Problem Statement

Given bar heights, find the area of the largest rectangle in the histogram.

Pattern: Monotonic Stack

Keep a stack of indices whose values are in increasing or decreasing order to find the next greater or smaller element efficiently.

Use this pattern when you need the next or previous greater or smaller element, or span and histogram style answers.

Approach

  1. Iterate through the array while keeping a stack of indices.
  2. Pop while the current value breaks the monotonic order and resolve the popped index.
  3. Push the current index and continue.

Pattern Template (Java)

Deque<Integer> stack = new ArrayDeque<>(); // stores indices
for (int i = 0; i < n; i++) {
    while (!stack.isEmpty() && nums[stack.peek()] < nums[i]) {
        int idx = stack.pop();
        // nums[i] is the next greater element of nums[idx]
    }
    stack.push(i);
}

Adapt this template to the exact rules of Largest Rectangle in Histogram: decide what state you track, what condition moves the loop forward, and what the final answer is.

Complexity

O(n) time because each index is pushed and popped once; O(n) space.

Interview Tips

  • Decide between storing values and storing indices, since indices are needed for distances.
  • Handle elements left on the stack after the loop.
  • Start with a brute-force idea, state its complexity, then explain how the Monotonic Stack pattern improves it.
  • Walk through a small example and at least one edge case (empty input, a single element, duplicates).

Continue Learning

Parent: DSA Interview Learning Path | Previous: Daily Temperatures | Next: Online Stock Span

Was this guide helpful?

CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.