Priority queues
medium 18 minA priority queue serves the item with the highest (or lowest) priority first, whatever order items arrived in.
See it run
Serve the most urgent item first: a binary heap keeps it at the root, so peek is O(1) and enqueue and dequeue are O(log n).
Operations
Enqueue (insert)
Add item 40 with priority 8 to a max-priority queue that holds priorities 5, 3 and 2. It goes in at the end and sifts up.
Step 1 of 6
A max-priority queue of three
The heap holds (priority, item) pairs. The ROOT has the highest priority, 5, and every parent beats its children. That is all a heap promises: it is not sorted.
Step 1: A max-priority queue of three
def enqueue(heap, item, priority): heap.append((priority, item)) # add at the end i = len(heap) - 1 while i > 0: # sift up parent = (i - 1) // 2 if heap[i][0] <= heap[parent][0]: break # parent wins: stop heap[i], heap[parent] = heap[parent], heap[i] i = parentheap = [(5, 10), (3, 20), (2, 30)]enqueue(heap, 40, 8)print(heap) # [(8, 40), (5, 10), (2, 30), (3, 20)]- Time
- O(log n)
- Space
- O(1)
- unsorted array
- O(1)
- sorted array
- O(n) shift
Enqueue = insert at the end, then sift UP. A higher priority bubbles towards the root.
In the real world
The same priority queues doing real jobs. Pick one and step through it.
Patients are treated by urgency, not arrival. Priorities: 4 critical, 3 serious, 2 moderate, 1 minor.
Step 1 of 9
The ER opens
heap
Treating patients in arrival order could be fatal: a heart attack cannot wait behind a headache. That sorting by urgency is triage, and a max-heap keeps the most urgent patient at the root, found in O(1). EMPTY
Step 1: The ER opens
import heapqfrom itertools import counter, tick = [], count()def arrive(name, priority): heapq.heappush(er, (-priority, next(tick), name))arrive("Liam", 2); arrive("Olivia", 1); arrive("Noah", 4)print(heapq.heappop(er)[2]) # Noaharrive("Ava", 3); arrive("James", 4)print([heapq.heappop(er)[2] for _ in range(len(er))])# ['James', 'Ava', 'Liam', 'Olivia']Common mistakes
The bugs interviewers watch for, with the fix beside each.
Forgetting heapq is a min-heap
criticalheapq always pops the smallest item. Pushing raw priorities to a 'highest first' queue serves the least urgent task first. Negate the priority (or the whole key) for max behaviour.
Wrongheapq.heappush(pq, (priority, task)) # pops LOWEST priorityRightheapq.heappush(pq, (-priority, task)) # pops highest priorityNo tie-breaker in the tuple
majorWhen two priorities are equal Python compares the next field. Strings then go alphabetically, not by arrival, and dicts or custom objects raise TypeError: '<' not supported.
Wrongheapq.heappush(pq, (-p, {"name": "Bob"})) # TypeError on a tieRightheapq.heappush(pq, (-p, next(counter), {"name": "Bob"}))Removing from the middle without repair
criticallist.remove or del on a heap leaves the remaining entries out of heap order, so later pops return the wrong item. Either re-heapify (O(n)) or mark the entry as removed and skip it when it is popped.
Wrongpq.remove(entry) # heap order brokenheapq.heappop(pq) # may not be the minRightremoved.add(entry_id) # lazy deletionwhile pq and pq[0][2] in removed: heapq.heappop(pq)Changing a priority in place
criticalOverwriting a heap slot with a new priority without sifting breaks the invariant: a now-urgent task may be buried under less urgent ones. Sift it, or push a fresh entry and skip the stale one later.
Wrongpq[i] = (new_p, count, task) # no siftRightheapq.heappush(pq, (new_p, next(counter), task))latest[task] = new_p # skip pops that do not matchTreating the heap list as sorted
majorOnly index 0 is guaranteed. pq[1] is not necessarily the second smallest, and printing the list does not show service order. Pop, or use heapq.nsmallest, to read things in order.
Wrongsecond = pq[1] # not guaranteedRightsecond = heapq.nsmallest(2, pq)[1]A max-heap of everything for top-k
minorPushing all n values and popping k is O(n log n) with O(n) memory. A size-k min-heap is O(n log k) with O(k) memory and works on an endless stream.
Wrongh = [-x for x in nums]; heapq.heapify(h)top = [-heapq.heappop(h) for _ in range(k)]Righttop = heapq.nlargest(k, nums) # size-k heap inside
Interview tips
How to explain it
- A priority queue is an ADT: insert with a priority, remove the highest (or lowest) priority first.
- A binary heap is the usual implementation: O(log n) enqueue and dequeue, O(1) peek, in a flat array.
- In Python: heapq with (priority, counter, item) tuples; negate the priority for max-first.
Spot it in the wild
- Top k, k-th largest, k closest: a size-k heap.
- Merge k sorted lists or streams: a heap of the k heads.
- Running median: two heaps. Shortest paths and MSTs: Dijkstra and Prim.
Memory tricks
- Hospital ER: the sickest are seen first, not the earliest.
- Enqueue = append + sift up. Dequeue = last to root + sift down.
- k largest uses a MIN-heap: the root is the bar to beat.
Watch out
- heapq is min-only: negate for max.
- Add a counter so ties never compare items.
- Never edit or remove a middle entry without sifting or lazy deletion.