Stack · Lesson

Stacks, explained: matching, undoing and evaluating expressions

Learn the stack: last in, first out, bracket matching, cancelling neighbours and evaluating expressions, with templates in Java, Python, C++ and JS.

1 pattern · 24 problems · Java, Python, C++ and JavaScript

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

What a stack does

A stack is a pile: you push on top and pop from the top, so the last thing in is the first thing out (LIFO). Both are O(1). You can also peek at the top without removing it.

That order is exactly what "the most recent unfinished thing" needs: the latest open bracket, the last operation to undo, the function call you are inside right now.

When a stack is the answer

  • Something opens and must close later, in the right order: brackets, tags, function calls.
  • The newest item reacts with the next one: adjacent duplicates cancel, asteroids collide, backspaces delete.
  • Expressions: operators wait on a stack until their operands are ready.
  • Nesting: 3[a2[c]], nested lists, directories in a path.

What it costs

OperationTimeSpace
push / pop / peekO(1)O(1)
Process a string with a stackO(n)O(n)
Search inside a stackO(n)O(1)

Built into your language

Library calls
Deque<Integer> st = new ArrayDeque<>();   // prefer ArrayDeque over the old Stack class
st.push(1); st.push(2);
st.peek();     // 2
st.pop();      // 2
st.isEmpty();  // false

Mistakes everyone makes

  • Popping or peeking an empty stack: check first.
  • Forgetting to check that the stack is empty at the end (unclosed brackets).
  • Using java.util.Stack: it is synchronized and slow. Use ArrayDeque.
  • Operand order for - and /: the second pop is the left operand.
Next: Stack problems: match, cancel, evaluate, nest →

The pattern

Each one: the idea and template, its variations with a worked example, then problems for you to solve.

  1. 1 Stack problems: match, cancel, evaluate, nest Push what is still open or pending; when the next item resolves it, pop. Brackets, cancelling neighbours, calculators and nested decoding are all this one move. 6 variations · 24 problems