1. Append at end
A new value first lands at the last array slot.
this.data.push(val)Typorithm · medium
Step 1 of 8 · intro card
Heaps
JavaScript has no built-in heap; insert by appending, then sift the value up while it is smaller than its parent.
A binary heap is stored in a flat array where a node at index i has parent (i - 1) >> 1.
Insertion appends the value to the end, then bubbles it up while it violates heap order.
Each swap moves the value one level toward the root, so insertion is O(log n).
Parent index is (i - 1) >> 1.
Append, then sift up.
Stop when parent <= child.
class MinHeap {
constructor() {
this.data = [];
}
push(val) {
this.data.push(val);
let i = this.data.length - 1;
while (i > 0) {
const parent = (i - 1) >> 1;
if (this.data[parent] <= this.data[i]) {
break;
}
[this.data[parent], this.data[i]] = [this.data[i], this.data[parent]];
i = parent;
}
}
}Connect each part of the code to the concept before you type.
A new value first lands at the last array slot.
this.data.push(val)In a 0-based array heap, a node's parent is (i - 1) >> 1.
const parent = (i - 1) >> 1Stop once the parent is no larger than the child.
if (this.data[parent] <= this.data[i]) {
break;
}Destructuring swaps the child up toward the root.
[this.data[parent], this.data[i]] = [this.data[i], this.data[parent]]Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.