Overview
Curated: · Written: · Reviewed:
Stacks
In one line
A LIFO structure where only the top is reachable, so each input resolves the most recent unresolved item. Reach for it when nesting, matching, nearest-previous or undo history decides the answer.
Key definitions
- Invariant: what the stack holds at every step. State it before the push and pop rules.
- Monotonic stack: kept sorted by value. A new element pops every top it dominates and resolves them.
- Sentinel: a value outside the input domain, appended so the loop drains the stack.
- Two-stack queue: an inbox and an outbox. Transfer only when the outbox is empty.
- Shunting-yard: infix to postfix using an operator stack ordered by precedence and associativity.
- Amortised O(1): average cost over a sequence, where occasional resizes cost O(n).
Formulas and complexity
Right-associative exponent, written as the code 2 ^ 3 ^ 2:
Left-associative division, written as the code 8 / 4 / 2:
Hypothetical profile:
How it works
- Each input either pushes itself (still unresolved) or pops the entries it resolves.
- The invariant fixes which entries are resolved, so the newest unresolved item resolves first.
- Each element is pushed once and popped at most once, which gives the linear bound.
- In postfix, pop the right operand first:
b = pop(); a = pop(); push(a op b). For5 1 2 + 4 * + 3 -the stack goes [5,1,2], [5,3], [5,3,4], [5,12], [17], [17,3], [14], so the service returns 14.
When to use and when not to
| Question | Stack? | Why |
|---|---|---|
| Matching nested delimiters | Yes | The newest opener closes first |
| Next greater or smaller element | Yes, monotonic | Each index is pushed and popped once |
| Undo and redo | Yes | LIFO history; a new action clears redo |
| Shortest path, unweighted | No, use a queue | A stack finds a path, not the shortest one |
| Interrupt path with a 2 µs budget | Linked, pooled nodes only | Array resize copies 65536 pointers in about 30 µs |
| Recursion over untrusted nesting | Explicit stack with a depth limit | The runtime stack is small and fixed |
Traps interviewers probe
- Popping an empty stack on a closer. Fix: check
if not stack: return Falsebefore the pop. Unbalanced input is a domain answer, not an exception. - Popping operands in the wrong order. Fix: pop the right operand first.
5 3 -gives 2; reversed pops give -2, while+still passes, which hides the bug. - Storing values instead of indices in a histogram pass. Fix: store indices, because the width of a popped bar runs from the element below it to the current index. Append a 0 sentinel so the stack drains.
- Transferring on every dequeue in the two-stack queue. Fix: transfer only when the outbox is empty. Pushing 1, 2, 3, popping, pushing 4 and popping three times returns 1, 4, 2, 3 under the buggy version.
- Assuming a bigger limit fixes recursion. Fix: convert to an explicit stack. Raising
sys.setrecursionlimitor-Xssmoves the failure without removing it, and CPython does not eliminate tail calls, sototal(xs, acc)still grows the stack linearly.
Interview tips
Open with the invariant: "The stack holds the unresolved items, newest on top, and each input resolves the entries it dominates."
Expect these follow-ups:
- Why is a nested pop loop linear? Count pushes, not loop bounds.
- Why indices rather than values? The answer needs a distance.
- What if the input is untrusted? Bound the depth and reject past it.
- Array or linked? Amortised copies win on throughput; a pooled linked stack wins on worst-case latency.
- Why not a stack for shortest path? On S to G the stack returns S, B, C, D, G, five nodes, where S, A, G is two edges. A queue gives the edge-count guarantee.
30-second outline:
- State the invariant.
- Derive push and pop from it.
- Each element is pushed once and popped once, so O(n).
- Name the edge case: the sentinel or the empty-stack guard.
- Name one trade-off: array versus linked, or stack versus queue.
Feedback on this overview
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.