A stack is a last-in, first-out (LIFO) collection: you add (push) and remove (pop) items at the same end, the top. Every operation is O(1), and that tiny interface turns out to model anything nested or reversible: function calls, undo history, matching brackets, expression parsing and depth-first search.
Think of it like
A stack of plates
In a cafeteria you put clean plates on top of the pile and take plates off the top. The plate you placed last is the first one used; the plate at the bottom waits until everything above it is gone. You never pull a plate from the middle. That restriction is exactly what makes a stack simple and fast.
How it works
A stack exposes a handful of operations, all at the top. Because nothing below the top is ever touched, each one is O(1) regardless of how many items the stack holds.
| Operation | Effect | Time |
|---|---|---|
push(x) | Place x on top | O(1) (amortized for array-backed stacks) |
pop() | Remove and return the top item | O(1) |
peek() / top() | Return the top item without removing it | O(1) |
isEmpty() / size() | Check whether anything is left | O(1) |
- LIFO
- Last in, first out: the most recently pushed item is the first popped.
- Top
- The single end where all pushes and pops happen.
- Underflow
- Popping or peeking an empty stack. Always check
isEmptyfirst. - Overflow
- Pushing onto a full fixed-capacity stack, or exhausting the call stack with deep recursion.
Array vs linked-list implementations
Dynamic array
- The top is the end of the array: push = append, pop = remove last
- O(1) amortized push because of occasional resizing
- Contiguous and cache-friendly; minimal overhead per item
- The default choice in practice
Linked list
- The top is the head: push and pop rewire the head pointer
- O(1) worst case, never a resize pause
- One allocation and one pointer per item
- Useful for lock-free stacks and persistent (immutable) stacks
| Language | Recommended stack | Push / pop / peek |
|---|---|---|
| Python | list (or collections.deque) | append(x) / pop() / s[-1] |
| Java | ArrayDeque<E> via the Deque interface | push(x) / pop() / peek() |
| C++ | std::stack<T> (adapter over std::deque by default) or std::vector | push(x) / pop() (returns void) / top() |
| JavaScript / TS | Array | push(x) / pop() / a[a.length - 1] |
java.util.Stack: it extends the synchronized Vector and pays for locking you do not need.Application: balanced parentheses
Brackets nest, and the most recently opened bracket must close first: exactly LIFO. Push every opening bracket; on a closing bracket, the top of the stack must be its matching opener. At the end, the stack must be empty.
| Input | Key moment | Result |
|---|---|---|
{[()]} | Each closer matches the opener on top: ( then [ then { | Balanced |
([)] | At ) the top is [, not ( | Not balanced |
((] | At ] the top is ( | Not balanced |
(() | Input ends with ( still on the stack | Not balanced |
()) | At the second ) the stack is already empty | Not balanced |
Application: undo, history and the call stack
- Undo and redo: every edit is pushed onto an undo stack. Undo pops it and pushes it onto a redo stack; any new edit clears the redo stack.
- Browser back button: visited pages form a stack; the forward button is a second stack, just like redo.
- The call stack: each function call pushes a frame with its locals and return address; returning pops it. That is why recursion can be rewritten with an explicit stack (Recursion).
- Depth-first search: replacing a queue with a stack turns breadth-first exploration into depth-first (Depth-First Search).
Application: infix to postfix (shunting-yard)
Humans write infix expressions like 3 + 4 * 2 - 1, which need precedence rules and parentheses. Postfix (Reverse Polish Notation) puts operators after their operands, 3 4 2 * + 1 -, and needs neither. Dijkstra's shunting-yard algorithm converts infix to postfix with one stack of pending operators.
- 1
Number
Send it straight to the output.
- 2
Operator
While the operator on top of the stack has higher precedence, or equal precedence and the new operator is left-associative, pop it to the output. Then push the new operator.
- 3
Left parenthesis
Push it. It acts as a floor that operators cannot be popped past.
- 4
Right parenthesis
Pop operators to the output until the matching
(appears; discard both parentheses. - 5
End of input
Pop every remaining operator to the output.
| Token | Action | Output | Operator stack |
|---|---|---|---|
3 | Output | 3 | (empty) |
+ | Push | 3 | + |
4 | Output | 3 4 | + |
* | Higher precedence than +: push | 3 4 | + * |
2 | Output | 3 4 2 | + * |
- | Pop * and + (not lower), push - | 3 4 2 * + | - |
1 | Output | 3 4 2 * + 1 | - |
| end | Pop the rest | 3 4 2 * + 1 - | (empty) |
3 + 4 * 2 - 1. The stack holds operators that are waiting for their right operand to be complete.Application: evaluating postfix
Postfix evaluation needs one stack of operands. Push numbers; on an operator, pop two values, apply the operator and push the result. The final value on the stack is the answer.
| Token | Stack after (top on the right) |
|---|---|
3 | 3 |
4 | 3, 4 |
2 | 3, 4, 2 |
* | 3, 8 |
+ | 11 |
1 | 11, 1 |
- | 10 |
-, compute second_popped - first_popped.8 - 3 - 2 and 2 ^ 3 ^ 2 to see associativity break ties.Min-stack: O(1) minimum
A classic design question: support push, pop, top and getMin, all in O(1). Scanning for the minimum is O(n). The trick is to remember, alongside each item, the minimum of everything at or below it. When you pop, the previous minimum is automatically restored.
| Operation | Stack of (value, min so far) | getMin() |
|---|---|---|
| push 5 | (5, 5) | 5 |
| push 3 | (5, 5) (3, 3) | 3 |
| push 7 | (5, 5) (3, 3) (7, 3) | 3 |
| pop | (5, 5) (3, 3) | 3 |
| pop | (5, 5) | 5 |
Complexity
| Operation | Array-backed | Linked-list | Notes |
|---|---|---|---|
| push | O(1) | O(1) | Array version is amortized |
| pop | O(1) | O(1) | |
| peek | O(1) | O(1) | |
| search for a value | O(n) | O(n) | Not what stacks are for |
| getMin (min-stack) | O(1) | O(1) | Store the running minimum with each entry |
| Balanced brackets | O(n) | O(n) | O(n) space in the worst case |
| Shunting-yard + evaluation | O(n) | O(n) | Each token pushed and popped at most once |
Implementation
The same interface built two ways: on a dynamic array (top at the end) and on a singly linked list (top at the head).
from typing import Generic, Optional, TypeVar
T = TypeVar("T")
class ArrayStack(Generic[T]):
def __init__(self) -> None:
self._items: list[T] = [] # top is the end of the list
def push(self, x: T) -> None: # amortized O(1)
self._items.append(x)
def pop(self) -> T: # O(1)
if not self._items:
raise IndexError("pop from empty stack")
return self._items.pop()
def peek(self) -> T: # O(1)
if not self._items:
raise IndexError("peek at empty stack")
return self._items[-1]
def __len__(self) -> int:
return len(self._items)
class _Node(Generic[T]):
def __init__(self, val: T, next: "Optional[_Node[T]]") -> None:
self.val = val
self.next = next
class LinkedStack(Generic[T]):
def __init__(self) -> None:
self._head: Optional[_Node[T]] = None # top is the head
self._size = 0
def push(self, x: T) -> None: # O(1) worst case
self._head = _Node(x, self._head)
self._size += 1
def pop(self) -> T:
if self._head is None:
raise IndexError("pop from empty stack")
node = self._head
self._head = node.next
self._size -= 1
return node.val
def peek(self) -> T:
if self._head is None:
raise IndexError("peek at empty stack")
return self._head.val
def __len__(self) -> int:
return self._size
for stack in (ArrayStack[int](), LinkedStack[int]()):
for x in (1, 2, 3):
stack.push(x)
print(stack.pop(), stack.peek(), len(stack)) # 3 2 2Key takeaways
- A stack is LIFO: push, pop and peek all happen at the top in O(1).
- Back it with a dynamic array (default) or a linked list (no resize pauses); in Java prefer
ArrayDequeoverStack. - Anything nested or "most recent first" is a stack problem: brackets, undo, the call stack, DFS.
- Shunting-yard converts infix to postfix with an operator stack; postfix is evaluated with an operand stack.
- A min-stack stores the running minimum with each entry to answer getMin in O(1).
Common pitfalls
- Popping or peeking an empty stack; check
isEmptyfirst, especially on closing brackets. - Forgetting the final emptiness check in bracket matching, so
"(()"is wrongly accepted. - Reversing operand order when evaluating postfix: the first value popped is the right operand.
- Using
java.util.Stack(synchronized, legacy) orLinkedList.get(i)instead ofArrayDeque. - Treating
^as left-associative in shunting-yard; exponentiation is right-associative.
Interview tips
- Say why a stack fits: "the most recent unmatched item determines the next step".
- For min-stack, mention both the pair approach and the auxiliary-stack approach and their space trade-off.
- Trace a short example on the whiteboard with the top on the right; it catches operand-order and empty-stack bugs.
Real-world applications
- Function call management (the call stack) and recursion.
- Undo/redo in editors and back/forward navigation in browsers.
- Parsers and compilers: bracket matching, expression evaluation, syntax checking.
- Depth-first search, backtracking and flood fill without recursion.
Practice problems
Test yourself
What is the postfix form of (1 + 2) * 3?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.