Heap algorithms
Heap algorithms use a binary heap to keep a running extreme (minimum or maximum) in O(log n) per update. In Python they are written with heapq on a list.
Detailed Explanation
A heap gives you the smallest item quickly without sorting the whole collection. Push and pop are O(log n). Peek is O(1). Build is O(n) with heapify. That is the engine for priority queues, Dijkstra, Huffman coding, "merge k sorted lists", and "streaming top k".
heapq is a min-heap. For a max-heap, store negated keys. For objects, store (priority, sequence, obj) so ties do not compare the objects. There is no built-in decrease-key; Dijkstra in Python pushes a new entry and ignores stale ones when they pop.
nsmallest and nlargest are heap algorithms you should not rewrite. For k much smaller than n they beat a full sort. For k close to n, sorted is simpler.
Heapsort is "heapify, then pop n times". It is O(n log n) and not stable. Python's Timsort is faster in practice and stable; you do not ship heapsort for general sorting.
A heap is not sorted. Iterating the list is not in order. Only heap[0] is meaningful without popping. If you need sorted output, pop until empty or call sorted.
Multi-way merge: put the head of each list on the heap with an origin index, pop the global min, push the next item from that list. That is O(n log k) for n items and k lists.
Code Examples
import heapq
import itertools
def merge_sorted(*streams: list[int]) -> list[int]:
heap = []
for i, stream in enumerate(streams):
if stream:
heapq.heappush(heap, (stream[0], i, 0))
out = []
while heap:
value, which, idx = heapq.heappop(heap)
out.append(value)
nxt = idx + 1
if nxt < len(streams[which]):
heapq.heappush(heap, (streams[which][nxt], which, nxt))
return out
print(merge_sorted([1, 4, 7], [2, 3, 8], [5])) # [1, 2, 3, 4, 5, 7, 8]# Dijkstra sketch: push (dist, node), skip stale pops.
def shortest(graph: dict[str, list[tuple[str, int]]], start: str) -> dict[str, int]:
dist = {start: 0}
heap = [(0, start)]
while heap:
d, node = heapq.heappop(heap)
if d != dist.get(node):
continue
for nxt, w in graph.get(node, []):
cand = d + w
if cand < dist.get(nxt, 1_000_000_000):
dist[nxt] = cand
heapq.heappush(heap, (cand, nxt))
return distCommon Gotchas
Treating the heap list as sorted
only the first element is the min. The rest is a heap tree.
Stale heap entries
after a better distance is found, old tuples remain. Ignore pops whose priority does not match the recorded best.
Comparing payloads
equal priorities fall through to the next tuple field. Add a counter.
`nlargest(k)` for k == n is a sort
use `sorted(..., reverse=True)` when you want the whole list.