Lesson 17 of 20
Min Heap
Min Heap
A Min Heap is a complete binary tree where every parent node is smaller than or equal to its children. The smallest element is always at the root.
Array Representation
A binary heap is stored as a flat array. For a node at index i:
- Left child:
2 * i + 1 - Right child:
2 * i + 2 - Parent:
Math.floor((i - 1) / 2)
1
/ \
3 5
/ \
7 9
Array: [1, 3, 5, 7, 9]
Insert (Bubble Up)
- Push the new value to the end of the array.
- Compare it with its parent — if smaller, swap them.
- Repeat until the heap property is restored.
insert(val) {
this.data.push(val);
let i = this.data.length - 1;
while (i > 0) {
const parent = Math.floor((i - 1) / 2);
if (this.data[i] >= this.data[parent]) break;
[this.data[i], this.data[parent]] = [this.data[parent], this.data[i]];
i = parent;
}
}
Extract Min (Bubble Down)
- Save the root (minimum).
- Move the last element to the root.
- Compare with children — swap with the smaller child if needed.
- Repeat until the heap property is restored.
extractMin() {
if (this.data.length === 0) return undefined;
const min = this.data[0];
const last = this.data.pop();
if (this.data.length > 0) {
this.data[0] = last;
// bubble down from index 0
}
return min;
}
Complexity
| Operation | Time |
|---|---|
| insert | O(log n) |
| extractMin | O(log n) |
| peek (min) | O(1) |
Your Task
Implement a MinHeap class with insert, extractMin, and peek methods.
JavaScript loading...
Loading...
Click "Run" to execute your code.