Step by step
The example above, written out — the same steps the animation plays.
- 1An empty stack. A stack is last in, first out (LIFO): you can only add or take from the top — like a pile of plates.
- 2push(3). 3 goes on top. O(1): nothing else moves.
- 3push(7). 7 goes on top. O(1): nothing else moves.
- 4push(1). 1 goes on top. O(1): nothing else moves.
- 5peek() → 1. peek looks at the top without removing it.
- 6pop(). Which value comes off?
- 7pop() → 1. 1 was the last one in, so it is the first one out.
- 8push(9). 9 goes on top. O(1): nothing else moves.
- 9pop(). Which value comes off?
- 10pop() → 9. 9 was the last one in, so it is the first one out.
- 11pop(). Which value comes off?
- 12pop() → 7. 7 was the last one in, so it is the first one out.
What's happening?
- push puts a value on top; pop removes and returns the top value; peek looks at it without removing it.
- Only the top is ever touched, so every operation is O(1).
- In the bracket checker, each opener waits on the stack and each closer must match the most recent opener — the top.
Complexity
- Time
- O(1) push, pop and peek
- Space
- O(n)
Where you'll meet it
Undo in editors, the browser Back button, the call stack that runs every function, expression parsing, and checking brackets in code and JSON.
Common mistake
Popping without checking that the stack is empty — an underflow error, or a crash.
FAQ
Stack vs queue?
A stack takes from the end it added to (LIFO); a queue takes from the other end (FIFO).
How do you check balanced brackets?
Push every opener; on each closer, the top must be its matching opener — pop it. At the end the stack must be empty.
What is a stack overflow?
When the call stack — the stack of running function calls — runs out of room, usually from recursion with no base case.