Stacks and queues
Stacks and queues are lists with rules about where items go in and come out. Those rules make them perfect for undo histories, parsing, task scheduling, and searching trees and graphs.
| Stack | Queue | |
|---|---|---|
| Order | LIFO: last in, first out | FIFO: first in, first out |
| Picture | A pile of plates | A line at a counter |
| Add | push (on top) |
enqueue (at the back) |
| Remove | pop (from the top) |
dequeue (from the front) |
| In Python | list: append() / pop() |
collections.deque: append() / popleft() |
All of these operations are O(1).
Stacks
Your program itself runs on a stack: each function call is pushed onto the call stack and popped when it returns, which is why too-deep recursion gives a "stack overflow" (RecursionError in Python).
Balanced brackets
A classic: every closing bracket must match the most recent unmatched opening bracket, which is exactly what the top of a stack holds:
Code editors, compilers and JSON parsers all do this.
Evaluating expressions
Reverse Polish notation (3 4 + 2 *) puts operators after their numbers, and a stack evaluates it in one pass:
Monotonic stack: the next greater element
For each day's temperature, how many days until a warmer one? Keep a stack of days still waiting for an answer; their temperatures are decreasing, so a warmer day resolves them from the top:
Each day is pushed and popped at most once: O(n), instead of O(n²) for scanning ahead from every day. Monotonic stacks also solve "stock span", "largest rectangle in a histogram" and similar problems.
Queues
Use collections.deque, which is O(1) at both ends. (list.pop(0) is O(n), because every element shifts.)
Queues model anything handled in arrival order: print jobs, web requests, messages between services (the Message queues lesson of the System Design track) and breadth-first search, coming up in the graphs lesson.
A queue to process tasks in rounds
Sliding window maximum with a deque
A monotonic deque keeps the indexes of candidates for the maximum, largest at the front:
Building one from the other
An interview classic: a queue using two stacks. Pushing goes to inbox; popping takes from outbox, refilling it (reversed) only when it's empty. Each item moves at most twice, so operations are amortised O(1):
Practice
- Implement a
MinStackwithpush,popandget_min, all O(1) (hint: a second stack of minimums). - Simplify a Unix path:
"/a/./b/../../c/"→"/c"using a stack. - Use a deque to check whether a string is a palindrome by popping from both ends.
1.Which structure gives "last in, first out"?
2.Why use collections.deque instead of list.pop(0) for a queue?
3.In the "days until warmer" solution, why is the total work O(n)?