Largest Rectangle in Histogram

Find the largest rectangle that can be formed in a histogram.

Pattern

Monotonic Stack

This problem follows the Monotonic Stack pattern, commonly found in the Stack category. Recognizing this pattern is key to solving it efficiently in an interview setting.

Approach

How to Solve It

Maintain increasing stack. On smaller bar, pop and calculate areas using stack for widths.

Key Insight

The width calculation uses the stack to find the left boundary — when you pop, everything between the new stack top and current index has height >= the popped bar.

Step-by-step

  1. 1Create a stack to store indices of bars
  2. 2For each bar (and a sentinel 0 at the end):
  3. 3While the stack is non-empty and current height < height at stack top:
  4. 4Pop the top, calculate the area using the popped height and width from stack
  5. 5Update the maximum area

Pseudocode

stack = []
maxArea = 0
for i in range(len(heights) + 1):
    h = heights[i] if i < len(heights) else 0
    while stack and heights[stack[-1]] > h:
        height = heights[stack.pop()]
        width = i if not stack else i - stack[-1] - 1
        maxArea = max(maxArea, height * width)
    stack.push(i)
return maxArea
Complexity Analysis

Time Complexity

O(n)

Space Complexity

O(n)
More Stack Problems

Master this pattern with YeetCode

Practice Largest Rectangle in Histogram and similar Stack problems with flashcards. Build pattern recognition through active recall.

Practice this problem