Practice Discrete Math

Algorithms / Monotonic Stack Boundaries

Least You Need to Know: Monotonic Stacks for Range Boundaries and Histogram Areas

Monotonic stacks do more than next-greater queries: they also expose the nearest smaller or larger boundary on each side. That boundary view powers classic problems like largest rectangle in a histogram and contribution counting.

The least you need to know

Key notation

prev smaller nearest earlier index with a strictly smaller value
next smaller nearest later index with a strictly smaller value
width count of indices between the two blocking boundaries

Tiny worked example

  • In a histogram, keep bars in increasing-height stack order.
  • When a shorter bar arrives, pop taller bars because their right boundary is now known.
  • The new stack top gives the left boundary for each popped bar.
  • Compute area immediately while that bar's maximal span is fully known.

Common mistakes

How to recognize this kind of problem

Start practice