💡
Exercise 75

Largest Rectangle Histogram 30 XP Hard

LeetCode Ctrl+Enter Run Ctrl+S Save

Given an array of bar heights representing a histogram, find the area of the largest rectangle that can be formed within the histogram.

heights = [2, 1, 5, 6, 2, 3] # # ┌──┐ # ┌──┤ │ # │ │ │ ┌──┐ # ┌──┐ │ │ │ ┌──┤ │ # │ │ │ │ │ │ │ │ # └──┴──┴──┴──┴──┴──┴──┘ # 2 1 5 6 2 3 # Largest rectangle: width=2 × height=5 = 10 # (bars at index 2,3 with heights 5,6 → min height 5)

This is a classic monotonic stack problem:

  • Maintain a stack of indices in increasing order of heights
  • When a bar is shorter than the stack top, pop and calculate area
  • Width = distance between current index and previous stack top
  • Time: O(n) — each bar is pushed and popped once

This is considered one of the hardest stack problems. It combines monotonic stacks with clever width calculation.

📋 Instructions
Implement `largest_rectangle(heights)` using a monotonic stack. Test with [2,1,5,6,2,3].
Use a stack of (index, height). When you find a shorter bar, pop taller bars and calculate area = height * (current_i - popped_index). Push the current bar with the leftmost valid start index. At end, process remaining stack entries with width extending to end.
🧪 Test Cases
Input
largest_rectangle([2, 1, 5, 6, 2, 3])
Expected
10
Test case 1
Input
largest_rectangle([2, 4])
Expected
4
Test case 2
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.