A stack is a collection where you can only add to the top and remove from the top. The last thing you put in is the first thing you take out, which is called LIFO ("last in, first out"). It sounds limiting, but that one rule is exactly what you need whenever things are nested or you need to undo the most recent step.
The picture: a pile of plates
- push: put a plate on top.
- pop: take the top plate off.
- peek: look at the top plate without taking it.
You never reach into the middle of the pile.
Stacks in code
You don't need a special class. A plain array is a stack if you only use its end:
const stack = []
stack.push('a') // ['a']
stack.push('b') // ['a', 'b']
stack.at(-1) // 'b' (peek at the top)
stack.pop() // 'b' → stack is ['a']
stack.length === 0 // is it empty?stack = []
stack.append("a") # ["a"]
stack.append("b") # ["a", "b"]
stack[-1] # "b" (peek at the top)
stack.pop() # "b" → stack is ["a"]
not stack # is it empty?Both push and pop are O(1): they only touch the end of the array.
Watch out
Don't use shift() / unshift() (JavaScript) or pop(0) / insert(0, x) (Python) for a stack. They work on the front of the array and have to move every other item, which is O(n).
Why "last in, first out" matters
Think of brackets: ( [ { } ] ). When you reach a closing bracket, which opening bracket does it belong to? Always the most recent one that's still open. That's the top of the stack.
The same shape appears all over programming:
- Nested things: brackets, HTML tags, folders inside folders.
- Undo: the most recent action is the first one you undo.
- Function calls: when function A calls B, and B calls C, C must finish first, then B, then A. Your language keeps a "call stack" for exactly this reason.
- Going back: the browser's back button returns to the most recent page.
The pattern
Most stack problems look like this:
const stack = []
for (const item of input) {
if (/* item "opens" something */) {
stack.push(item)
} else {
// item "closes" or resolves the most recent open thing
const top = stack.pop()
// check top against item...
}
}
// often: whatever is left on the stack was never closedHow to recognize this category
Think "stack" when the problem:
- involves matching pairs that can be nested (brackets, tags)
- talks about "the most recent" item
- needs to undo or backtrack one step at a time
- processes expressions (like
3 + (4 * 2))
Common mistakes
- Popping from an empty stack. Always check
stack.length > 0(orif stack) before you pop, unless your language returns something harmless. - Forgetting to check the stack at the end. Leftover items usually mean something was opened and never closed.
- Using a stack when order should be first-in-first-out. If the oldest item should come out first (like a line at a shop), you want a queue, not a stack. Queues come up in the Trees and Graphs categories.