Stack
Last in, first out: brackets, parsing, undo and the next-greater family.
5 pages, free to read
- 1
Stacks & queues basics
BeginnerA stack gives back the most recently added item first (last in, first out) and a queue gives back the oldest first (first in, first out); both do their core operations in O(1).
8 min read - 2
Balanced brackets & validation
BeginnerPush every opening bracket and, on each closing bracket, check that it matches the top of the stack; the string is valid only if every check passes and the stack ends empty.
9 min read - 3
Monotonic stack
IntermediateKeep a stack whose values are always increasing or decreasing; when a new element breaks the order, everything it pops has just found its next greater (or smaller) element, giving O(n) for problems that look O(n^2).
11 min read - 4
Evaluating expressions
IntermediateStacks turn arithmetic text into answers: postfix (RPN) needs one stack of numbers, and normal infix expressions need either a sign-aware number stack or two stacks (numbers and operators) to respect precedence and parentheses.
11 min read - 5
Designing with stacks (min stack, queue via stacks)
IntermediateDesign questions ask you to add a feature (like get_min in O(1)) or build one structure from another (a queue from two stacks); the trick is storing a little extra state per element or moving elements lazily so every operation stays O(1) or O(1) amortised.
10 min read