Question presented to candidate:
"Python does not have a PriorityQueue class in the core containers, but it has heapq. How does it work? What data structure sits underneath, what do push and pop cost, and how would you use it to build a task scheduler or find the top k items?"
What a strong answer should cover:
heapqis a set of functions over a plainlistkept as a binary min-heap:heap[k] <= heap[2k+1]andheap[k] <= heap[2k+2], soheap[0]is always the smallest. The list is not sorted.- Costs:
heappushandheappopare O(log n),heap[0]is O(1),heapifyis O(n);heappushpopandheapreplacecombine a push and a pop in one sift. - Priority queues with
(priority, counter, item)tuples: the counter breaks ties in FIFO order and stops Python from comparing the items; lazy deletion for cancelled entries. nsmallest,nlargestandmerge: top-k in O(n log k) and lazy merging of sorted inputs;sorted()ormin()are better when k is large or 1.- Max-heaps: negate numeric keys on 3.11; Python 3.14 added public
heappush_max,heappop_max,heapify_maxand friends. - CPython detail: the C module
_heapqreplaces the Python code, only<is used, andheappopuses a "sift to a leaf, then back up" variant that saves comparisons.
Code / implementation expected: Yes โ push and pop a few values, show the list is a heap and not sorted, and build a small priority queue with a tie-breaker.