When to Use

Pattern triggers

Look for these signals in the problem:

  • "Next greater/smaller element": Monotonic stack finds the first element to the right that's larger or smaller than current.
  • "Previous greater/smaller element": Same concept looking leftward, often computed simultaneously.
  • "Span" calculations: How far back can you go while maintaining some property (like stock span).
  • "Histogram" or "rectangle" area problems: Track boundaries where height changes using monotonic stack.
  • "Contribution counting": When each element contributes to multiple subarrays, monotonic stack efficiently counts contributions.