The home where you level up

Save my spot

Min Heap

Term side of the Card.
Topic: Tree
Unit title: Min Heap
Categories: Data structure
Explanation side of the Card

Explanation: The complete binary tree structure with the lowest value at the root and each parent node less than or equal to its children. Used in priority queues and finding minimum elements efficiently.

Example

Wrongjs
function pop(heap) {
  heap.sort((a, b) => a - b);
  return heap.shift();
}
Rightjs
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.

The home where you level up

Daily 3-minute lessons to understand your AI's code.

No spam — just launch news.
Unsubscribe anytime. · Privacy Policy

Analytics cookiesWe'd like to use analytics cookies to see which pages are useful. They're set only if you accept. Privacy Policy