Stacks and queues: last-in-first-out and first-in-first-out
The two simplest ordered containers, what each one is for, and the classic bracket-matching problem that every candidate should be able to write.
In short
A stack gives back the most recent item first (LIFO); a queue gives back the oldest first (FIFO). Both do push and pop in O(1). Nested structure → stack. Processing in order of arrival → queue.
Two shapes, two jobs
Stack (LIFO)
- Undo history, browser back button
- The call stack of recursion
- Matching brackets, evaluating expressions
- DFS (depth-first search)
Queue (FIFO)
- Print jobs, task queues
- Level by level (BFS)
- Streams of events in order
- Rate limiting windows
In Python use a list as a stack and collections.deque as a queue. In Java use ArrayDeque for both. A JavaScript array works as a stack; for a queue shift() is O(n), so use an index or a deque.
The classic: matching brackets
Whenever structure is nested (brackets, HTML tags, function calls) the thing that closes first is the thing that opened last: a stack.
stack
1def is_valid(s):2 pairs = {')': '(', ']': '[', '}': '{'}3 stack = []4 for ch in s:5 if ch in pairs:6 if not stack or stack.pop() != pairs[ch]:7 return False8 else:9 stack.append(ch)10 return not stack
Variables
Where else it shows up
- Implement a queue with two stacks (and the reverse): a classic design question.
- Min stack: also keep the minimum so far with each element to answer "what's the min?" in O(1).
- Evaluate reverse Polish notation: push numbers, on an operator pop two and push the result.
- Replace recursion with an explicit stack to avoid stack overflow on deep inputs.
Key takeaways
- 01Stack = LIFO, queue = FIFO; push and pop are O(1).
- 02Nested or matching structure points to a stack.
- 03Level-by-level or arrival order points to a queue.
- 04An explicit stack can replace recursion.
Check your understanding
1 of 3
Which structure returns the most recently added item first?
Related topics
Monotonic stack
Keep a stack of items still waiting for an answer, in sorted order. When a new item resolves some of them, pop and answer. Each item is pushed and popped once: O(n).
8 min read →BFS & DFS
A graph is nodes and edges. BFS uses a queue and explores in rings: the first time it reaches a node is via a shortest path (unweighted). DFS uses a stack (or recursion) and dives deep. Both cost O(V + E). Always keep a visited set, or cycles will loop forever.
10 min read →