Heaps & Priority Queues: The Ultimate Guide
A single, authoritative reference โ from first principles to production systems across DS, AI, ML, and LLM infrastructure. Python-first, complexity-annotated, and interview-ready.
1. Core Concepts & Definitionsโ
1.1 Formal Definitionโ
A heap is a complete binary tree that satisfies the heap property:
- Min-Heap: for every node
N,key(N) โค key(children(N)). The minimum sits at the root. - Max-Heap: for every node
N,key(N) โฅ key(children(N)). The maximum sits at the root.
"Complete binary tree" is the load-bearing phrase: every level is fully filled except possibly the last, which fills left to right. This shape guarantee is why a heap can live in a flat array with no pointers, and why its height is always โlogโ nโ.
A priority queue (PQ) is an abstract data type (ADT) โ a contract, not an implementation. It supports:
insert(item, priority)extract_top()โ remove and return the highest-priority itempeek()โ inspect the top without removing
1.2 Intuitive Plain-English Explanationโ
๐ก The core intuition: A heap is a tournament bracket that only bothers to keep the champion on top. Unlike a sorted list, it does not waste effort fully ordering everyone โ it only guarantees that the single most important element is instantly reachable, and that fixing the order after a change is cheap (
O(log n), the height of the tree).
A sorted array answers "what's the max?" in O(1) but costs O(n) to insert. An unsorted array inserts in O(1) but costs O(n) to find the max. A heap is the elegant middle: O(log n) insert and O(log n) removal of the extreme, with O(1) peek. It buys balance by refusing to sort what you'll never ask for.
1.3 Relationship Between the Two Structuresโ
| Priority Queue | Heap | |
|---|---|---|
| What it is | Abstract data type (interface) | Concrete data structure |
| Defines | What operations exist | How they're implemented |
| Analogy | "A list that pops the most important item" | The array-tree that makes that fast |
โ ๏ธ Most common misconception: "Heap == priority queue." They are not synonyms. A PQ can be built from a sorted array, a balanced BST, or a heap. A binary heap is simply the most common and usually best implementation. Conversely, a heap can be used for things that aren't queues at all (heapsort, selection). Keep the ADT/implementation distinction crisp โ interviewers probe it.
1.4 The Array Representation (why heaps are cheap)โ
A complete binary tree maps to a 0-indexed array with pure arithmetic โ no pointers, great cache locality:
parent(i) = (i - 1) // 2
left_child(i) = 2*i + 1
right_child(i) = 2*i + 2
Index: 0 1 2 3 4 5
Value: [1, 3, 6, 5, 9, 8]
Tree view (min-heap):
1 <- index 0 (root, the minimum)
/ \
3 6 <- index 1, 2
/ \ /
5 9 8 <- index 3, 4, 5
Verify: left_child(0)=1 (value 3), right_child(0)=2 (value 6), parent(4)=(4-1)//2=1 (value 3). โ