Min Heap
Example
function pop(heap) {
heap.sort((a, b) => a - b);
return heap.shift();
}function pop(heap) {
const top = heap[0];
const last = heap.pop();
if (heap.length > 0) {
heap[0] = last;
siftDown(heap, 0);
}
return top;
}Moving the last item to the root and sifting down is O(log n); sorting plus shift() costs O(n log n) per pop.
Common mistakes
- Sorting and calling
shift()for every pop, which is O(n log n) each time. - Sifting down toward the wrong child and breaking the heap order.
Key points
- Extract moves the last item to the root and sifts it down, so each pop is O(log n).
- Sift down swaps with the smaller of the two children, not with the first child that is smaller.
- Keeping the k largest items uses a min heap capped at size k, which is O(n log k).
- Objects are compared with a comparator such as
(a, b) => a.priority - b.priority.
Interview questions
When do I use a min heap instead of a sorted array?
When you insert and remove items repeatedly. A heap does both in O(log n), while keeping an array sorted costs O(n) per insert.
Is a min heap sorted?
No. Only the root is guaranteed to be the minimum; siblings and items on the same level are in no fixed order.
Where are min heaps used?
In Dijkstra's shortest path algorithm, task schedulers, merging k sorted lists, and event queues ordered by time.
