A deque supports efficient operations at both ends. A heap keeps its smallest item accessible without fully sorting its internal array.
Compare undo, arrival-order service and priority service, and inspect what each structure actually guarantees.
Removing the oldest event and selecting the most urgent event are different jobs. A deque makes operations at either end cheap; a heap maintains access to the smallest priority. Inspect what each preserves, including tied priorities and bounded-history eviction, before using it for a queue that must not lose or reorder work accidentally.

Undo history for a text editor
An editor keeps the last few actions so Ctrl+Z has something to undo. A plain list
works, but popping the oldest action off the front is slow once the list is long
— every remaining item has to shift over one slot. deque avoids the shift:
A bounded history is even more useful — keep only the last 3 actions, automatically:
from collections import deque
history = deque(maxlen=3)
for action in ["type a", "type b", "type c", "type d"]:
history.append(action)
print(list(history))Preparing this topic’s interactive investigation…
A hospital triage queue
Patients don't arrive in the order they should be seen — a 1 (most urgent) should
jump ahead of a 2 that arrived first. heapq keeps the smallest priority number
on top no matter what order things were pushed in:
heapq compares the whole tuple, so on a tied priority it looks at the next
element to break the tie. That's fine for two numbers — it breaks the moment the
second element isn't comparable, like two dicts:
import heapq
heap = []
heapq.heappush(heap, (2, {"name": "Asha"}))
heapq.heappush(heap, (2, {"name": "Bea"}))
heapq.heappop(heap)A running counter fixes it — ties now break by arrival order, and the payload can be anything:
A heap promises a minimum, not a sorted list
The heap invariant is local: for each index i, the parent is no greater than
children at 2*i + 1 and 2*i + 2, when they exist. Following those relations
makes the root no greater than any descendant. It does not order siblings.
This prints True, False, then the sorted extraction order. Reading heap[0]
is constant-time; removing it repairs a path through the tree, costing
O(log n). heapify builds the invariant in O(n). Do not edit a queued
priority in place: that can break the invariant without any warning.
For equal priorities, (priority, sequence_number, payload) makes the policy
explicit and prevents comparisons from reaching unorderable payloads. In a
long-running queue, use one continually increasing sequence number, not an
index restarted for each incoming batch.
Now compare the bounded deque: appending into a full history deliberately
evicts an item, whereas an ordinary task queue should preserve pending work.
Choose maxlen only when dropping old entries is part of the contract. Test the
triage function with two equal priorities whose names are reverse alphabetic;
that exposes accidental name-based ordering which unique priorities conceal.
Merge two sorted leaderboards
Two already-sorted lists need to become one sorted list — say, scores from two game
servers. Sorting the combined list again throws away work you already paid for;
heapq.merge combines sorted inputs in one pass without re-sorting (both inputs must already follow the same sort order):
heapq also has two shortcuts for "give me the extremes without sorting the whole
list": nlargest(n, items) and nsmallest(n, items).
Quick practice
from collections import deque
dq = deque([2, 3, 4])
dq.appendleft(1)
dq.append(5)
print(dq.popleft(), dq.pop())This prints 5, not the smallest value in the list. Heapify it first.
🎯 Your turn
Write triage_order(patients). Each patient is [priority, name] — a lower
number is more urgent. Return the names in the order they should be seen: by
priority first, and by arrival order (their position in the list) for a tie.
triage_order([[2, "Asha"], [1, "Bea"], [2, "Cy"]])→["Bea", "Asha", "Cy"]triage_order([])→[]
Hint: push (priority, index, name) onto a heap as you loop with enumerate,
then heapq.heappop() everything off in order and collect the names.
Press ▶ Run and hit ✓ Check. ✅
Practice — level up
0/5 solvedSolve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.
Write rotate_list(items, k) that rotates items right by k positions (a negative k rotates left), using deque.rotate.
Write is_palindrome_deque(s) using a deque: repeatedly compare and remove the front and back characters with popleft()/pop() until fewer than 2 remain. Return False the moment two compared characters differ.
Write kth_smallest(nums, k) returning the kth smallest value in nums (k=1 is the smallest), using heapq.nsmallest instead of sorting the whole list.
Write merge_leaderboards(a, b): a and b are already sorted ascending. Return one sorted list with everything from both, using heapq.merge instead of concatenating and re-sorting.
Write nearest_k_points(points, k): points is a list of [x, y] pairs. Return the k points closest to (0, 0), nearest first, without computing a real square root. Use heapq.nsmallest with a key.