Stack & Monotonic Stack
Signal: matching or nesting (brackets, tags), "most recent unmatched", evaluating expressions, undo, and "next greater / smaller element" or "how far until…" questions.
Core idea: a stack gives O(1) access to the most recent item. A monotonic stack keeps its elements sorted (increasing or decreasing). When a new element breaks the order, everything it "beats" is popped, and at that moment you know their answer.
Templates
python
# Matching / nesting
stack = []
for ch in s:
if opens(ch): stack.append(ch)
elif not stack or not matches(stack.pop(), ch): return False
return not stack
# Next greater element to the right (monotonic decreasing stack of indices)
ans = [-1] * n
st = []
for i, x in enumerate(a):
while st and a[st[-1]] < x:
ans[st.pop()] = x # x is the next greater for that index
st.append(i)Each index is pushed once and popped at most once, so the whole scan is O(n), even though there's a while inside the for. Expect interviewers to ask you to justify this (amortized analysis).
| Want | Stack order | Pop when |
|---|---|---|
| Next greater element | decreasing | a[top] < x |
| Next smaller element | increasing | a[top] > x |
| Previous greater/smaller | same, but read the stack top after popping |