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.
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
| Operation | Time | Space |
|---|---|---|
| push / pop / peek | O(1) | O(1) |
| Process a string with a stack | O(n) | O(n) |
| Search inside a stack | O(n) | O(1) |
Built into your language
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 st = [] # a list is a stack
st.append(1); st.append(2)
st[-1] # 2 (peek)
st.pop() # 2
not st # False: not empty stack<int> st;
st.push(1); st.push(2);
st.top(); // 2 (peek)
st.pop(); // removes 2, returns nothing
st.empty(); // false const st = []; // an array is a stack
st.push(1); st.push(2);
st[st.length - 1]; // 2 (peek)
st.pop(); // 2
st.length === 0; // 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. UseArrayDeque. - Operand order for
-and/: the second pop is the left operand.
The pattern
Each one: the idea and template, its variations with a worked example, then problems for you to solve.