# Min Heap

> The Min Heap is a complete binary tree data structure where each parent node is less than or equal to its child nodes.

## What is a min heap and when should I use it?

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.

- Topic: Tree
- Type: data structure

## Example

Wrong:

```js
function pop(heap) {
  heap.sort((a, b) => a - b);
  return heap.shift();
}
```

Right:

```js
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.

## Related cards

- [Max Heap](https://wonderium.dev/algorithms/max-heap.md)
- [Dijkstra's Algorithm](https://wonderium.dev/algorithms/dijkstra-algorithm.md)
- [Top K Elements](https://wonderium.dev/algorithms/top-k-elements.md)
- [Queue](https://wonderium.dev/algorithms/queue.md)
- [Binary Tree](https://wonderium.dev/algorithms/binary-tree.md)

---

- Level: [Algorithms](https://wonderium.dev/algorithms.md)
- HTML version: https://wonderium.dev/algorithms/min-heap
- Last updated: 2026-11-25
