AlgoViz

Stack

easy 14 min

A stack is a linear data structure where items are added and removed at the same end, the top.

Remember it

The few things worth knowing cold, and how to make them stick.

Memory hook

Last in, first out: the plate you put down last is the plate you pick up first.

A pile of pancakes. You add each new pancake on top and you always eat the top one first. To reach one lower down, you have to eat everything above it.

Cheat sheet

push
O(1) amortised
pop
O(1)
peek
O(1)
is_empty, size
O(1)
search
O(n), not a stack operation
Space
O(n)
Python stack
list with append / pop
Underflow
pop or peek on empty
Overflow
push past capacity, or recursion with no base case

Spot it when you see

  • Matching brackets, tags or any pairs that nest.
  • Undo and redo, or back and forward.
  • "Most recent" or "last seen" must be handled first.
  • Nested structures: expressions, paths like a/b/../c, decoding strings like 3[ab].
  • DFS or backtracking you want to write without recursion.
  • Next greater or next smaller element, daily temperatures, histogram areas (monotonic stack).
  • Reversing a sequence.
  • Evaluating an expression in postfix or with operator precedence.

Tricks that stick

  • LIFO: Last In, First Out. The last thing you put in is the first thing you take out.
  • Rhyme: "Stack it high, grab from the sky, last to arrive is first to say goodbye."
  • Picture a tall tower you can only reach at the top. To get lower, remove everything above.
  • Overflow = Over capacity or Over recursion, like a glass spilling over the top.
  • Underflow = Under zero elements, like sucking air from an empty cup.
  • Check before you touch: is_full() before push, is_empty() before pop.

Do not forget

  • Using insert(0, x) or pop(0) on a Python list: O(n) each, keep the top at the end.
  • Popping or peeking without checking for empty first.
  • Forgetting the final empty check in bracket matching, so (( passes.
  • Using a stack where the problem wants FIFO order or BFS.
  • Deep recursion hitting Python's default limit of about 1000 frames.
  • In a monotonic stack, storing values when the answer needs indexes.