Stack
Think about stacking plates in the kitchen. You put a plate on top. Then another. Then another. When you need a plate, you grab the one on top — not the one at the bottom.
That's a stack. It follows one simple rule: Last In, First Out — or LIFO for short.
Push and Pop
There are only two main moves:
- Push — add something on top
- Pop — remove the top item
You can also peek — look at the top item without removing it.
Where do stacks appear?
Everywhere! Your browser's back button uses a stack. When you hit Ctrl+Z to undo, that's a stack. In algorithms, Depth-First Search uses a stack to explore paths. Even your code runs on a call stack — every time a function calls another function, it gets pushed on. When it returns, it gets popped off.
← → arrow keys to step · click elements to interact
Stack Operations
Why is push and pop \(O(1)\)?
The stack always knows where the top is. Adding or removing from the top requires zero searching — it's one step, always. That's why both operations are instant, no matter how tall the stack gets.
Why is search \(O(n)\)?
If you're looking for a specific value buried somewhere in the stack, you'd have to pop items one by one until you find it. In the worst case, you check every item.
The call stack
When your code runs, each function call is pushed onto a call stack. When the function finishes, it's popped off. If you call functions too deeply without returning, you get a stack overflow — the stack runs out of space!
Complexity
Balanced Parentheses Checker
Quick check
Continue reading