Sub topic 6
Stacks, queues and deques: ordering by arrival
This chapter assumes you know Python lists, loops and functions, and that you have a rough idea of Big-O. Earlier chapters covered the cost of list operations. Here the question is different. Sometimes the right structure is the one that limits how you reach your data, so that items come out in the order they arrived.
Three arrival orders
- A stack is last in, first out (LIFO). You add and remove at the same end. The most recent item comes out first.
- A queue is first in, first out (FIFO). You add at the back and remove from the front. The oldest item comes out first.
- A deque (double-ended queue, pronounced "deck") allows adds and removes at both ends. It can act as a stack, a queue, or both at once.
Stacks: undo what you did last
Use a stack when the latest unfinished thing must be resolved first. Typical cases are matching brackets, undo history, and replacing recursion with an explicit loop. A Python list works well because append and pop at the end run in O(1) amortized time.
def is_balanced(text):
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for ch in text:
if ch in "([{":
stack.append(ch)
elif ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False
return not stack
print(is_balanced("{[()]}")) # True
print(is_balanced("([)]")) # FalseEach closing bracket must match the most recent opening bracket that is still open. That is exactly what the top of the stack holds.
Queues and deques: first come, first served
Use a queue when work must be handled in arrival order, such as job scheduling or level-by-level traversal. Do not build one with list.pop(0). Removing the first element shifts every other element, so each removal costs O(n). Use collections.deque, where popleft is O(1).
from collections import deque
jobs = deque()
jobs.append("a")
jobs.append("b")
jobs.append("c")
print(jobs.popleft()) # a
recent = deque(maxlen=3)
for n in range(5):
recent.append(n)
print(list(recent)) # [2, 3, 4]The maxlen argument gives a fixed-size window. When it is full, adding an item silently drops one from the opposite end. That suits "keep the last N events".
Operation costs
| Operation | list | deque |
|---|---|---|
| Add or remove at the right end | O(1) amortized | O(1) |
| Add or remove at the left end | O(n) | O(1) |
| Index into the middle | O(1) | O(n) |
| Membership test (`x in ...`) | O(n) | O(n) |
The last two rows show the trade-off. A deque is built for its ends. If you also need frequent random indexing, a deque is the wrong choice.
Common errors
- Using
list.pop(0)orlist.insert(0, x)in a loop. The cost grows quadratically with the number of items. - Using a stack when the problem needs oldest-first order. A traversal that uses a stack goes deep before wide. One that uses a queue goes level by level. The order you pick changes the result, not only the speed.
- Indexing into the middle of a deque in a hot loop.
- Using a stack or queue when you need the smallest item rather than the oldest or newest. That calls for a heap, covered in the next chapter.
Exercise
A program stores incoming requests in a Python list and handles them with requests.pop(0). It slows down badly as the backlog grows. What is the cause, and what is the fix?
Show answer
Removing the first element of a list shifts all remaining elements, so each removal is O(n) and processing a backlog of n requests is O(n^2). Replace the list with collections.deque, add with append, and remove with popleft, which is O(1).