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
- A heap fills up level by level, from left to right, with no gaps. That's why it can be packed tightly into an array. The root is at index 0.
- The children of index
iare at index2 * i + 1(left) and2 * i + 2(right). The children of the number 4 (index 1) are at index 3 and 4: the numbers 8 and 10. - The parent of index
iis at indexMath.floor((i - 1) / 2)(Math.floorrounds down). The parent of the number 12 (index 5) is at index 2: the number 6. - The rule only holds between a parent and its children: 2 ≤ 4, 2 ≤ 6, 4 ≤ 8, and so on. Siblings (children of the same parent) have no rule between them, so a heap's array isn't necessarily sorted.
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:
- The root is taken out as the result.
- The number at the very back moves to the root.
- 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
- Stopping the sink too early. The replacement at the root has to keep sinking as long as there's a smaller child, not just swap once. In the
extractMinexample above, 9 sinks twice. - Swapping with the wrong child. When sinking, swap with the smaller child. Swap with the bigger one and the small child ends up below a bigger number, which breaks the heap rule.
- Thinking a heap is sorted.
[1, 4, 2, 8, 10, 12, 6]is a valid heap, but it isn't sorted. All that's promised is that the root is the smallest. Want them in order? Take them out one by one withextractMin(). - Using
sortin the exercise.sortgives the right numbers too, but the exercise checks that you make anew MinHeap()and callextractMin().
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).