#84

Largest Rectangle in Histogram

Hard Monotonic stack

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Bars of width 1 have given heights. Return the area of the largest rectangle that fits inside the histogram.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: the largest rectangle inside the bars.

Why this works: each bar's best rectangle stretches until a shorter bar on each side. An increasing stack finds both sides when a bar is popped.

Example: [2, 1, 5, 6, 2, 3]

2 pops 6 → 6×1, then 5 → 5×2 = 10best 10

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Forgetting the sentinel at the end, so bars left in the stack are never measured.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(n).
Topic: Stack & Queue
🎬 Episodes 46–52: video coming soon