heapq

A heap is a list arranged so the smallest item is always at index 0. The heapq module works on plain lists:

  • heapify(xs) arranges a list in place, O(n).
  • heappush(h, x) and heappop(h) add and remove the smallest, O(log n).
  • nlargest(k, xs) and nsmallest(k, xs) give the top or bottom k.

To use a heap as a priority queue, push (priority, item) tuples. Tuples compare by their first item, so the lowest priority number comes out first. If two priorities tie, Python compares the items next, which fails for things like dicts. Add a counter as a tie breaker: (priority, count, item).

heapq is a min-heap. For a max-heap, push negated numbers. Python 3.14 adds heappush_max and friends, but negating works in every version.

Heaps power "top k", "merge k sorted lists" and Dijkstra's shortest path.

Run it, then turn nums into a max-heap by negating.