← chapter

Binary heaps and priority queues

Complete binary tree in an array: every parent beats its children. Always grab the extreme — the priority queue.

Weak order, one strong guarantee

Watch push (up) and pop (down)

Push 1 → sifts up to the root. Pop → last leaf to root, sifts down. Never fully sorted — just parent < children.

Costs

peek O(1) · push/pop O(log n) · build O(n). heapq ≈13× faster (C).

Only the extreme is fast

Takeaway

Minimum effort to answer one question: what's the extreme? The engine of Dijkstra, Prim, Huffman, schedulers. Next: tries.