Python 3.11+
The examples use standard Python containers and syntax available in the supported browser runtime; Priority Queue itself is taught as an interview abstraction.
Verify in Python docs(opens in a new tab)A priority queue removes the best live task according to an explicit priority and tie policy. Use tuple entries with a unique order field, then validate versions when lazy updates leave obsolete entries in the heap.
1 practice exercise1 interview problem
Recognize it when The next task is chosen by priority rather than arrival order.
Checking your account…
A priority queue is an interface: removal returns the pending item with the best priority, not the oldest item. A heap is the usual implementation. Separating the interface from the storage matters because priorities, tie rules, and updates belong to the queue contract rather than heap mechanics.
Python’s heapq removes the smallest tuple. Decide whether a smaller number means higher priority,
or negate a numeric field consistently for maximum priority. The root represents the next valid item
to process; other pending items need not be globally sorted.
Tuple entries such as (priority, counter, item) establish a total order. The monotonic counter
preserves insertion order among equal priorities and prevents Python from comparing arbitrary item
objects as a final tie breaker.
import heapq
def schedule(tasks):
heap = []
for counter, (priority, label) in enumerate(tasks):
heapq.heappush(heap, (priority, counter, label))
return [heapq.heappop(heap)[2] for _ in range(len(heap))]Implement schedule(tasks). Each task is (priority, label); return labels from smallest priority to largest while preserving input order for ties.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
import heapq
def schedule(tasks):
heap = []
for counter, (priority, label) in enumerate(tasks):
heapq.heappush(heap, (priority, counter, label))
return [heapq.heappop(heap)[2] for _ in range(len(heap))]The heapq priority-queue notes(opens in a new tab) describe this pattern. Choose the tuple fields deliberately; an accidental name or object field can silently create the wrong tie policy.
heapq has no efficient search-and-update operation. Push a new entry and record its current
(priority, version) pair in a dictionary. When popping, discard entries whose complete pair no longer matches the current
record. The invariant is that the first non-stale root is the best live item.
import heapq
def updated_schedule(initial, updates):
heap = []
current = {}
counter = 0
for item, priority in [*initial, *updates]:
current[item] = (priority, counter)
heapq.heappush(heap, (priority, counter, item))
counter += 1
order = []
while heap:
priority, version, item = heapq.heappop(heap)
if current.get(item) != (priority, version):
continue
order.append(item)
del current[item]
return orderImplement updated_schedule(initial, updates). Push every priority update lazily and return each item once using only its latest priority and stable update order.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
import heapq
def updated_schedule(initial, updates):
heap = []
current = {}
counter = 0
for item, priority in [*initial, *updates]:
current[item] = (priority, counter)
heapq.heappush(heap, (priority, counter, item))
counter += 1
order = []
while heap:
priority, version, item = heapq.heappop(heap)
if current.get(item) != (priority, version):
continue
order.append(item)
del current[item]
return orderRun the actual lazy-update Lab where task a improves and task b worsens. The obsolete b entry has a better numeric priority than its latest version, but it must be skipped because the stored version no longer matches.
print(updated_schedule([('a', 5), ('b', 2)], [('a', 1), ('b', 6)])) followed by print(updated_schedule([], []))
| Step | Executed statement | State | Why |
|---|---|---|---|
| 1 | current[item] = (priority, counter); heapq.heappush(heap, (priority, counter, item)) |
current = {'a': (1, 2), 'b': (6, 3)}; stored versions = 4 |
Every update supersedes dictionary metadata while old tuples remain stored. |
| 2 | priority, version, item = heapq.heappop(heap) |
entry = (1, 2, 'a'); current['a'] = (1, 2) |
The smallest root is a’s latest eligible version. |
| 3 | order.append(item); del current[item] |
order = ['a']; current = {'b': (6, 3)} |
Removing live metadata prevents duplicate later processing. |
| 4 | if current.get(item) != (priority, version): continue |
old entries (2, 1, 'b') and (5, 0, 'a') skipped |
b was superseded and a was already consumed; neither old root is live. |
| 5 | order.append(item); del current[item]; return order |
entry = (6, 3, 'b'); result = ['a', 'b'] |
The current b version remains eligible despite its worse numeric priority. |
| Output | |
|---|---|
| 1 | ['a', 'b'] |
| 2 | [] |
Checking priority alone is insufficient when equal priorities can be assigned repeatedly; the unique version distinguishes those entries too. Deleting live metadata after processing guarantees later obsolete tuples cannot emit the same item again.
Lazy deletion may leave old entries in memory until they reach the root. Complexity counts every pushed version, although each stale version is eventually popped at most once.
Use a priority queue when pending work changes over time and repeatedly removing the best item drives the algorithm, as in Dijkstra or scheduling. Use a bounded heap for a static/streaming top-k summary, a FIFO queue for equal-priority breadth order, and sorting when one final complete order is enough.
TypeError.Define whether smaller or larger is better and specify the tie rule. State what makes a heap entry live and why skipping stale roots is safe. Give O(log n) per pushed or popped entry and explain that lazy duplicates affect n. This is different from the bounded top-k heap, whose root is the weakest retained answer rather than the next task to execute.
Update a Bounded Heap(opens in a new tab) contrasts static candidate selection. Seat Reservation Manager(opens in a new tab) uses the priority-queue contract to repeatedly allocate the smallest available seat.
Python 3.11+
The examples use standard Python containers and syntax available in the supported browser runtime; Priority Queue itself is taught as an interview abstraction.
Verify in Python docs(opens in a new tab)Interview bounds depend on the stated representation, input model, and real Python operations.
| Operation | Average | Worst | Interview note |
|---|---|---|---|
| Push or pop one of m entries | O(log(m + 1)) | O(log(m + 1)) | m counts stored versions, including stale ones; tuple priority comparisons have bounded cost. |
| Build and drain schedules | O(m * log(m + 1)) | O(m * log(m + 1)) | m initial/update entries; each version is pushed and popped once. Current metadata/output uses at most the number of logical items. |
O(m) for push or pop one of m entries; O(m) for build and drain schedules.
These are the mistakes most likely to survive a happy-path example and fail a boundary case.
A two-field tuple reaches dictionary payload comparison when priorities tie and raises TypeError.
Prevent it: Insert a unique counter before the payload field.
heapq.heappush(heap, (1, first))
heapq.heappush(heap, (1, second))heapq.heappush(heap, (1, 0, first))
heapq.heappush(heap, (1, 1, second))Where you will hit this: Keep the K Largest Values(opens in a new tab)
Comparable labels avoid an exception but sort alphabetically, violating authored input order for ties.
Prevent it: Place an input-order counter before labels in the comparison tuple.
for priority, label in tasks:
heapq.heappush(heap, (priority, label))for counter, (priority, label) in enumerate(tasks):
heapq.heappush(heap, (priority, counter, label))Where you will hit this: Keep the K Largest Values(opens in a new tab)
Two versions can have the same numeric priority. Only the latest counter identifies the live entry.
Prevent it: Compare the complete (priority, version) pair against current metadata.
live = current[item][0] == prioritylive = current.get(item) == (priority, version)Where you will hit this: Seat Reservation Manager(opens in a new tab)
Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.
python-docs · checked 2026-07-27