sagelearnai

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).

WantStack orderPop when
Next greater elementdecreasinga[top] < x
Next smaller elementincreasinga[top] > x
Previous greater/smallersame, but read the stack top after popping

Problems

  1. Valid Parentheses (Easy): Push openers, pop & match on closers
  2. Min Stack (Medium): Store (value, min-so-far) pairs
  3. Evaluate Reverse Polish Notation (Medium): Operands on a stack; operators pop two
  4. Decode String (Medium): Stack of (previous string, repeat count) at each '['
  5. Asteroid Collision (Medium): Stack of survivors; incoming left-mover fights right-movers on top
  6. Next Greater Element I (Easy): Monotonic stack over nums2 → map of next greater
  7. Next Greater Element II (Medium): Monotonic stack over the array traversed twice (circular)
  8. Daily Temperatures (Medium): Monotonic decreasing stack of indices
  9. Online Stock Span (Medium): Stack of (price, span) with decreasing prices; merge spans
  10. Car Fleet (Medium): Sort by position desc; count increases in arrival time
  11. Largest Rectangle in Histogram (Hard): Increasing stack; pop gives a bar's maximal span
  12. Backspace String Compare (Easy): Process both from the end, skipping characters erased by '#'
  13. Simplify Path (Medium): Split by '/', use a stack for directory names
  14. Remove K Digits (Medium): Monotonic increasing stack; pop larger digits while k > 0
  15. Minimum Remove to Make Valid Parentheses (Medium): Stack of unmatched '(' indices; drop unmatched ')' on the fly
  16. Basic Calculator II (Medium): Stack of terms; apply * and / immediately, sum at the end
  17. Sum of Subarray Minimums (Medium): Each element contributes arr[i] × left × right (monotonic stack)
  18. Basic Calculator (Hard): Running result + sign; push (result, sign) at '(' and combine at ')'
  19. Maximal Rectangle (Hard): Each row → histogram heights; largest rectangle in histogram
  20. Maximum Frequency Stack (Hard): freq map + stack per frequency level