What is a monotonic stack and its applications?

Why Interviewers Ask This

Mid-level Data Structures & Algorithms roles require deep understanding of this topic. Interviewers ask this to separate candidates who truly understand the mechanics from those who only know surface-level concepts.

Answer

A monotonic stack maintains elements in monotonically increasing or decreasing order by popping elements that violate the order before pushing new ones. The key insight: while we pop an element x because of a new element y (y > x for increasing monotonic stack), y is the "next greater element" of x. Monotonic decreasing stack: maintains elements in decreasing order from bottom to top. Used for "next greater element" problems. Monotonic increasing stack: used for "next smaller element" problems. Classic problems: (1) Next Greater Element: for each element, find the next element to its right that is greater. Traverse left to right, pop elements smaller than current — current is their answer; push current. O(n); (2) Largest Rectangle in Histogram: use monotonic increasing stack of bar indices; when a shorter bar is found, pop and compute rectangles. O(n); (3) Maximal Rectangle in binary matrix (builds on histogram); (4) Trapping Rainwater: monotonic stack or two-pointer; (5) Stock Span Problem; (6) Daily Temperatures; (7) Remove K Digits to minimize the number. Template: maintain stack, for each element check if it should trigger pops, process pops, push current. O(n) — each element pushed and popped at most once.

Common Mistake

Rushing to answer is a common mistake. Take two seconds to structure your response: definition → example → trade-off. This structure makes complex Data Structures & Algorithms answers easy to follow.