Stack & Queue
Read a little, play a little. No scary maths, and no rush.
Two lines, opposite manners
A stack is a cafeteria tray pile: last tray placed is the first one taken (LIFO). A queue is a checkout line: first in, first out (FIFO). Both do two operations in O(1) — add and remove from the correct end — and both power far more algorithms than their simplicity suggests.
Valid parentheses: the stack classic
Brackets must close in reverse order of opening — exactly LIFO behavior. Push every opener; on a closer, pop and check it matches:
def valid(s):
st, m = [], {')': '(', ']': '[', '}': '{'}
for ch in s:
if ch in '([{':
st.append(ch) # opener? remember it
elif not st or st.pop() != m[ch]:
return False # closer with no match
return not st # leftovers mean unclosed
Trace "([)]": push (, push [, then ) meets [ — mismatch, false. Counting brackets would wrongly pass this; only order-aware matching works.
Where each one hides
- Stack: undo buttons, browser back, expression evaluation, DFS (recursion is a stack), and the monotonic stack — keep elements increasing to find each item's "next greater" in O(n), a beloved hard-pattern gateway.
- Queue: printer jobs, BFS levels, task schedulers, anything "fair" where arrival order is the priority.
Use the right container in Python
A plain list makes a fine stack: append and pop work at the end in O(1). It makes a poor queue: pop(0) removes from the front, which shifts every remaining element, so it is O(n). For queues use collections.deque, whose popleft is O(1). On a BFS over a million nodes, that one choice decides whether the solution passes.
The monotonic stack, traced
"For each number, find the next larger number to its right" for [2, 1, 5, 3]. Keep a stack of positions still waiting for their answer:
- 2: nothing waiting, so push it.
- 1: not larger than 2, so push it too.
- 5: larger than 1, so 1's answer is 5; pop. Larger than 2, so 2's answer is 5; pop. Push 5.
- 3: not larger than 5, so push it.
- End: 5 and 3 never found a larger number, so their answer is −1.
Result: [5, 5, -1, -1]. Each position is pushed once and popped at most once, so the whole thing is O(n) instead of O(n²) for checking every pair.
A queue built from two stacks
A favorite interview question: build a queue using only stacks. Push new items onto an "in" stack. To remove, take from an "out" stack; if it is empty, first pour everything from "in" into "out", which reverses the order so the oldest item ends up on top. Each item is moved at most once, so every operation is O(1) on average.
Common mistakes
- Popping an empty stack. Check before popping, as the parentheses solution does with
not st. - Forgetting leftovers. After the loop, items still on the stack usually mean something was never closed or never answered.
Spotting it in a problem statement
Words like "most recent", "undo", "nested", or "matching" point to a stack. Words like "in the order received", "level by level", or "nearest first" point to a queue.
Remember this
- Nesting/reversal → stack. Fairness/levels → queue.
- Valid parentheses is the 5-minute stack check every interviewer trusts.
Check your understanding
5 questions · first-try answers earn the most XP
My notes
Saved in this browser. Highlight a line above and save it, or write it in your own words.
Nothing saved yet. Your highlights will live here.
References
Finished reading?
Ticking it here also ticks the chapter in the sidebar, the section count and your streak — it is all one number.
Related chapters
Practice this pattern elsewhere
More problems to practise on external judges. Both links open the site home rather than a specific set, so you can pick problems for this pattern.
Spotted a mistake or want a topic covered? Report an issue