Skip to contentKEEP THE CRAFTTHE SANCTUARY

Priority Queue

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…

Priority Queue Code Labs

Mental Model

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.

Priority Is the Removal Contract

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.

Encode Stable Composite Priorities

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.

Preserve Stable Priority Ties

Reference
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))]
Practice

Implement schedule(tasks). Each task is (priority, label); return labels from smallest priority to largest while preserving input order for ties.

Public tests

  • Verify explicit tie ordering

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Preserve Stable Priority Ties

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.

Skip Stale Entries

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.

Discard Stale Priority Entries

Reference
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 order
Practice

Implement updated_schedule(initial, updates). Push every priority update lazily and return each item once using only its latest priority and stable update order.

Public tests

  • Verify stale versions are skipped

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Discard Stale Priority Entries

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 order

Trace Old Priority Entries Becoming Ineligible

Run 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.
Print 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.

Choose a Priority Queue or Heap Selection

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.

Priority Ties and Stale Entry Mistakes

  • Omitting a tie counter can compare non-orderable task objects and raise TypeError.
  • Updating only the dictionary without pushing a new heap entry hides the improved priority.
  • Returning the first popped tuple without checking staleness processes obsolete work.
  • Negating priority on insertion but not when interpreting output reverses semantics.
  • Assuming one heap entry per logical item understates lazy-update memory.

Explain It in an Interview

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 Version Note

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)

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Push or pop one of m entriesO(log(m + 1))O(log(m + 1))m counts stored versions, including stale ones; tuple priority comparisons have bounded cost.
Build and drain schedulesO(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.

Space

O(m) for push or pop one of m entries; O(m) for build and drain schedules.

Assumptions

  • m counts stored versions, including stale ones; tuple priority comparisons have bounded cost.
  • m initial/update entries; each version is pushed and popped once. Current metadata/output uses at most the number of logical items.

Invariants Worth Saying Aloud

  1. Smaller numeric priority is processed first in these Labs.
  2. A unique counter resolves equal priorities before payload comparison.
  3. An entry is live only if both its priority and version match current[item].

When To Use Or Avoid Priority Queue

Use It When

  • Use heap entries when best-pending-item extraction drives the algorithm.
  • Keep current-version metadata when pushing updates lazily.

Choose Another Tool When

  • Use a FIFO queue when all tasks must follow arrival order.
  • Use a bounded heap when the answer is a top-k summary rather than task processing.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Comparing non-orderable payloads on equal priorities

A two-field tuple reaches dictionary payload comparison when priorities tie and raises TypeError.

Prevent it: Insert a unique counter before the payload field.

Avoid

heapq.heappush(heap, (1, first))
heapq.heappush(heap, (1, second))

Use instead

heapq.heappush(heap, (1, 0, first))
heapq.heappush(heap, (1, 1, second))

Using labels as an accidental tie policy

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.

Avoid

for priority, label in tasks:
    heapq.heappush(heap, (priority, label))

Use instead

for counter, (priority, label) in enumerate(tasks):
    heapq.heappush(heap, (priority, counter, label))

Accepting an obsolete version because its priority matches

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.

Avoid

live = current[item][0] == priority

Use instead

live = current.get(item) == (priority, version)

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.