// Add item and bubble up
insert(value: number): void {
this.bubbleUp(this.items.length - 1);
// Remove and return smallest item
extractMin(): number | undefined {
if (this.items.length === 0) return undefined;
if (this.items.length === 1) return this.items.pop();
const min = this.items[0];
this.items[0] = this.items.pop()!;
// Helper: bubble up to maintain heap property
private bubbleUp(index: number): void {
const parent = Math.floor((index - 1) / 2);
if (index > 0 && this.items[index]! < this.items[parent]!) {
[this.items[index]!, this.items[parent]!] = [
// Helper: bubble down to maintain heap property
private bubbleDown(index: number): void {
const left = 2 * index + 1;
const right = 2 * index + 2;
if (left < this.items.length && this.items[left]! < this.items[smallest]!) {
right < this.items.length &&
this.items[right]! < this.items[smallest]!
if (smallest !== index) {
[this.items[index]!, this.items[smallest]!] = [
this.bubbleDown(smallest);
const heap = new MinHeap();
console.log(heap.extractMin()); // Output: 1
console.log(heap.extractMin()); // Output: 3