Stack
easy 14 minA stack is a linear data structure where items are added and removed at the same end, the top.
Video lesson · Chapter 1 of 6
The bottom tray is trapped
Stack of Trays — Stack
1:23Reel
Read caption
Try grabbing the bottom tray. You can reach it only after lifting the ones above it. Push C, A, T. Peek and you'll see T with all three trays still in place. Pop them and the letters come out T, A, C. The same last-in, first-out rule reverses the word in code.
How it works
Step through the idea, or press Play.
Push onto the top. A new item always goes on top of the pile, never in the middle or at the bottom
Understand it
Start here
What a stack is
A stack is a linear data structure where items are added and removed at the same end, called the top. The last item in is the first item out: LIFO, Last In, First Out. Everything else follows from that one rule.
LIFO order
The newest item always leaves first.
One access point
Only the top can be read or removed. Items below are out of reach.
Reverse on the way out
Push 1, 2, 3 and you pop 3, 2, 1. That is why stacks reverse things.
The picture
LIFO in one picture

- 1PushAdd an item on top
- 2PeekRead the top, change nothing
- 3PopRemove the top, newest first
Every stack operation touches the top and nothing else.
The API
Core operations
| Operation | What it does | On 10, 20, 30, 40 |
|---|---|---|
push(x) | Puts x on top | push(50) gives 10, 20, 30, 40, 50 |
pop() | Removes and returns the top | returns 40, leaves 10, 20, 30 |
peek() | Returns the top without removing it | returns 40, stack unchanged |
is_empty() | True when there is nothing to pop | False |
size() | Number of items | 4 |
Searching for a value is not a stack operation. If you find yourself needing it often, a stack is the wrong tool.
Under the hood
How push and pop work
push(x)
pop()
peek() follows the same path but stops after reading the value.Complexity
What each operation costs
| Operation | Time | Space | Why |
|---|---|---|---|
push | amortised | Writes one slot at the top; a dynamic array sometimes doubles | |
pop | Removes one slot at the top | ||
peek | Reads the top directly | ||
is_empty, size | The size is tracked as items come and go | ||
| search | Has to walk down the whole stack | ||
| the stack itself | One slot per stored item |
Why push stays O(1) on a dynamic array
Comparison
Stack vs queue vs array
| Stack | Queue | Array | |
|---|---|---|---|
| Order | LIFO | FIFO | Any index |
| Insert | at the top | at the back | at the end, in the middle |
| Remove | at the top | at the front | at the end, in the middle |
| Find | by index, by value | ||
| Typical use | Undo, DFS, parsing | BFS, scheduling | Random access |
Use a stack when
- The most recent item must be handled first.
- Things nest: brackets, tags, function calls.
- You do DFS or backtracking, or turn recursion into a loop.
- You build undo and redo, or back and forward.
Do not use a stack when
- You need random access by index (use an array).
- You need first-in, first-out order or BFS (use a queue).
- You need access at both ends (use a deque).
- You search for values often (use a set or dict).
Implementation
Three ways to build one
Dynamic array
Top is the end of the list:
append(x)andpop(). The usual choice in Python.Linked list
Top is the head:
head = Node(x, head). Never resizes, costs one pointer per node.Fixed-size array
A preallocated array plus a
topindex. Must check for full before every push.
stack = []stack.append(10) # pushstack.append(20)stack.append(30)print(stack[-1]) # peek -> 30print(stack.pop()) # pop -> 30print(len(stack) == 0) # is_empty -> Falseclass Node: def __init__(self, val, next=None): self.val = val self.next = nextclass LinkedStack: def __init__(self): self.head = None self.count = 0 def push(self, val): self.head = Node(val, self.head) # new node becomes the top self.count += 1 def pop(self): if self.head is None: raise IndexError("pop from empty stack") val = self.head.val self.head = self.head.next self.count -= 1 return vals = LinkedStack()s.push(1)s.push(2)print(s.pop(), s.pop()) # 2 1In the wild
Where stacks run
Function calls
Each call pushes a frame with its arguments, locals and return address. Each return pops it.
Undo and redo
Editors push every action. Undo pops it onto a redo stack.
Browser history
Back and Forward are two stacks that trade pages.
Parsing
Compilers check brackets and evaluate expressions with operator precedence.
DFS and backtracking
Push a choice, explore, pop to go back. Mazes, N-Queens, tree walks.
Next greater element
A monotonic stack answers it in one pass, .
Browser back and forward with two stacks
Deep dive
The call stack up close
When main() calls calculate(), which calls multiply(), three frames pile up. Each function waits for the one above it. Returns happen in reverse, newest first.
Calls push frames, returns pop them
Errors
Overflow and underflow
class SafeStack: def __init__(self, max_size=1000): self.items = [] self.max_size = max_size def push(self, item): if len(self.items) >= self.max_size: raise OverflowError("stack overflow: stack is full") self.items.append(item) def pop(self): if not self.items: raise IndexError("stack underflow: stack is empty") return self.items.pop()s = SafeStack(max_size=2)s.push("a")s.push("b")print(len(s.items) >= s.max_size) # True: one more push overflowsPreventing overflow
- Give every recursion a reachable base case.
- Check capacity before pushing onto a fixed-size stack.
- Turn very deep recursion into a loop with an explicit stack.
Preventing underflow
- Check
is_empty()before everypop()orpeek(). - Treat empty input as its own case.
- Validate that input is balanced, for example brackets.
Pattern spotting
Spotting a stack problem
Should I use a stack?
Matching brackets
Push openers; on a closer, pop and check it matches.
Monotonic stack
Keep values sorted; pop whatever breaks the order. Daily temperatures, next greater.
Expression evaluation
One stack for operands, one for operators, or a single stack for postfix.
Backtracking
Push a state before exploring it, pop to go back.
Matching brackets, one character at a time
((.Recap
Key takeaways
Key points
- A stack is LIFO: the last item pushed is the first popped.
push,pop,peek,is_emptyandsizeare ; search is ; space is .- In Python, use a list and keep the top at the end:
appendandpop(). - The call stack, undo, browser history and parsing all run on stacks.
- Overflow is pushing past capacity or recursing without a base case; underflow is popping from empty.
- Signals: newest first, nesting, matching, DFS, next greater element.