Builds onArrays and strings
01The idea
A stack is a list where you only add and remove items at one end, the top. Adding an item to the top is called a push, and removing the item on the top is called a pop. You can also look at the top without removing it. All three take O(1).
The item you remove is always the one you added last. That is the rule called last in, first out.
In Python, a list works as a stack. append pushes, pop() pops, and stack[-1] is the top. In Java, use ArrayDeque with push, pop and peek.
A stack fits any problem where the newest unfinished item is the one you deal with next. When you read a closing bracket, it must match the newest open bracket. When you press undo, it removes the newest change. When a function returns, the computer goes back to the newest paused call. That last one is the call stack from the recursion lesson.
02How to spot it
Use a stack when:
- items open and close, and each close must match the most recent open: brackets, tags, nested calls
- a new item can cancel or combine with the item right before it, such as undo stars, backspaces or equal letters next to each other
- you evaluate an expression and need to hold numbers until an operator arrives
- you want to run a recursive walk with a loop, such as a depth-first search without recursion
The signal is "the most recent one". If the problem only ever needs the newest item that is still open, a stack gives it in O(1).
When the rule is "the oldest one first", you need a queue instead. When it is "the smallest one first", you need a heap.
Sign in to read the rest of this lesson
The worked example, the interactive visualization, the code template and a short quiz that marks the lesson as done in your study plans.
Sign in to continue