Heap / Priority Queue — Data Structures

A priority queue serves the most important item first, and a heap is how you build one. A heap is a binary tree stored in an array. A min-heap keeps every…

In a hospital emergency room, a patient who came in at nine with a small cut can be seen after an urgent patient who came in at ten. The order of arrival isn't used. The most urgent patient is seen first, whenever they came in.

A line like this is called a priority queue: the most important item is served first, not the one that arrived first. In the emergency room, the patients are the items in the line, and a patient's urgency is their priority (for example 1 for the most urgent). The most common way to build one is with a heap. A heap is a binary tree with one rule between every parent and its children. In a min-heap, every parent is smaller than or equal to its children, so the smallest number is always at the root, the very top, and it is served first. A max-heap is the opposite: the largest is at the root.

A heap is stored in an array

This is a min-heap of six numbers, as a tree and as an array:

        2              index:  0  1  2  3   4   5
      /   \            array: [2, 4, 6, 8, 10, 12]
     4     6
    / \   /
   8  10 12

insert: in at the back, then up

A new number always goes at the very back of the array. As long as it's smaller than its parent, the two swap. This move up is called sift up. Example: insert(1) into the heap above.

Step Array What happens
1 [2, 4, 6, 8, 10, 12, 1] 1 goes in at index 6. Its parent is at index 2: the number 6
2 [2, 4, 1, 8, 10, 12, 6] 1 < 6: swap. Now at index 2, its parent is the number 2
3 [1, 4, 2, 8, 10, 12, 6] 1 < 2: swap. It reached the root: stop

If its parent is already smaller, the new number stops earlier.

extractMin: take the root, then sink its replacement

extractMin takes out the smallest number in three steps:

  1. The root is taken out as the result.
  2. The number at the very back moves to the root.
  3. That number sinks: as long as it has a smaller child, it swaps with the smallest child. This move down is called sift down.

Example: extractMin() on [1, 3, 5, 7, 9].

Step Array What happens
1 [9, 3, 5, 7] 1 is taken, 9 (the last one) moves to the root
2 [3, 9, 5, 7] 9's children are 3 and 5. The smallest is 3, and 3 < 9: swap
3 [3, 7, 5, 9] 9's only child now is 7. 7 < 9: swap. No more children: stop

The result is 1, and the heap becomes [3, 7, 5, 9]. Its new root is 3, the next smallest number.

How fast is it? Looking at the smallest only means reading index 0: O(1), the time stays the same. In insert and extractMin, a number moves up or down at most as many levels as the tree is tall. A heap is only about log n levels tall: 1,000 items is about 10 levels, 1,000,000 items about 20. So both are O(log n).

Using a heap: the k smallest numbers

In the exercise, the MinHeap class already has insert, extractMin and size. You just use it:

const heap = new MinHeap();
for (const num of [5, 2, 8, 1]) heap.insert(num);

console.log(heap.extractMin()); // 1
console.log(heap.extractMin()); // 2
console.log(heap.size());       // 2 (5 and 8 are left)

Each extractMin() gives you the smallest number still left, and size() is how many numbers are left. So to get the k smallest numbers (k is how many you're asked for): put them all in, call extractMin() k times in a loop, and collect the results in an array. They come out from smallest to largest on their own. For a huge amount of data with a small k, there is a cheaper way: a max-heap kept at no more than k numbers (the largest is thrown out each time it holds more than k) takes only O(n log k), and in Python heapq.nsmallest(k, data) gives the k smallest numbers in order directly.

⚠️ A sift down that stops halfway, and a heap taken for sorted

TL;DR: A priority queue serves the most important item first, and a heap is how you build one. A heap is a binary tree stored in an array. A min-heap keeps every parent ≤ its children, so the smallest number is always at the root (index 0). The children of index i are at 2 * i + 1 and 2 * i + 2, and its parent is at Math.floor((i - 1) / 2). insert puts a number at the back of the array, then moves it up while it's smaller than its parent. extractMin takes the root, moves the last number to the root, then sinks it (moves it down). Looking at the root is O(1), insert and extract are O(log n).

⚡ The smallest is always at the root

Meaning: A priority queue serves the most important item first, not the one that arrived first. The most common way to build one is a heap: a binary tree with a rule between every parent and its children. In a min-heap, every parent is ≤ its children (smaller or equal), so the smallest number is always at the root and is served first. A heap is stored in an array, with the root at index 0. Siblings (children of the same parent) have no rule between them, so a heap's array isn't necessarily sorted.

⚡ Child and parent indexes

Guess first: a heap fills an array level by level, from left to right, and every parent has at most two children. In the heap [2, 4, 6, 8, 10, 12], at which indexes are the children of the number 4 (index 1)?

Index 3 and 4: the numbers 8 and 10. The formula: the children of index i are at 2 * i + 1 and 2 * i + 2, and its parent is at Math.floor((i - 1) / 2) (rounded down).

Meaning: Because it fills up with no gaps, a heap can be packed tightly into an array. The places of the children and the parent are calculated from the index.

⚡ Up and down

Write:

const heap = new MinHeap();
for (const num of [5, 2, 8, 1]) heap.insert(num);

console.log(heap.extractMin()); // 1
console.log(heap.extractMin()); // 2

Meaning: MinHeap is a min-heap class that the exercise already gives you. insert puts a number at the back of the array, then moves it up while it's smaller than its parent. extractMin takes the root (the smallest number), moves the last number to the root, then sinks it, always swapping with the smaller child. Both are O(log n), and looking at the root is O(1).

What you will learn