Pattern 1: Top K Elements
Keep a min-heap of size K. For each new element, if it's larger than heap top, pop and push. After all elements, heap contains top K largest.
Pattern 2: K-way Merge
Push first element of each sorted list into min-heap with list index. Pop minimum, push next from same list. Merges K sorted lists in O(n log K).
Pattern 3: Running Median
Two heaps: max-heap for lower half, min-heap for upper half. Balance sizes to differ by at most 1. Median = top of larger heap (or average of both tops).
Pattern 4: Dijkstra / Greedy
Min-heap drives greedy selection: always process the cheapest/closest element next. O((V+E) log V) for shortest paths.
Start with min-heap [1,4,7,9,5]. First: push 3 (appears at bottom, sifts up past 7 and 4 until heap property holds). Then: pop-min (root 1 → last element placed at root, sifts down). Watch the array form in each caption — it reinforces heap-as-array indexing.
🧠 Under the Hood
A heap is stored as a contiguous array — no pointers needed. The parent-child relationship is purely arithmetic. This gives excellent cache performance: sift-up/sift-down access memory in a predictable order. std::priority_queue wraps a std::vector using exactly this layout.
⚖️ When to Use / When NOT to Use
std::set (RB-tree) — O(log n) for insert, delete-by-value, and ordered iteration. Heap only supports O(1) peek-min and O(log n) pop-min.std::max_element / std::min_element — a single O(n) scan. Building a heap is also O(n) but adds code complexity.🚫 Common Misconceptions
priority_queue is a max-heap by default (largest on top). For a min-heap, use priority_queue<int, vector<int>, greater<int>>. This trips up candidates expecting Python's heapq behavior.