Min Heap (Heapify Up & Down) Visualizer & Step-by-Step Algorithm Solution

Complete binary min-heap implementation visualizing _heapifyUp() on insertion and _heapifyDown() on root extraction across both binary tree and 0-indexed array representations.

Category: heap | Difficulty: Medium

Tags: Min Heap, Binary Heap, Heapify Up, Heapify Down, Priority Queue, Complete Binary Tree

Min Heap (Heapify Up & Down)

MinHeap Backing Array (heap[0 .. n-1])
100%
state
heapSize0
operationIdle
Initialization
1/52
Explanation

Initialized empty MinHeap. Processing 9 operations.

Source Code
1class MinHeap {
2 private heap: number[] = [];
3
4 public add(value: number): void {
5 this.heap.push(value);
6 this._heapifyUp();
7 }
8
9 public poll(): number | null {
10 if (this.heap.length === 0) return null;
11 if (this.heap.length === 1) return this.heap.pop()!;
12 const root = this.heap[0];
13 this.heap[0] = this.heap.pop()!;
14 this._heapifyDown();
15 return root;
16 }
17
18 private _heapifyUp(): void {
19 let index = this.heap.length - 1;
20 while (index > 0) {
21 const parentIndex = Math.floor((index - 1) / 2);
22 if (this.heap[parentIndex] <= this.heap[index]) break;
23 [this.heap[parentIndex], this.heap[index]] = [this.heap[index], this.heap[parentIndex]];
24 index = parentIndex;
25 }
26 }
27
28 private _heapifyDown(): void {
29 let index = 0;
30 const length = this.heap.length;
31 while (true) {
32 const leftChildIndex = 2 * index + 1;
33 const rightChildIndex = 2 * index + 2;
34 let smallestIndex = index;
35 if (leftChildIndex < length && this.heap[leftChildIndex] < this.heap[smallestIndex]) {
36 smallestIndex = leftChildIndex;
37 }
38 if (rightChildIndex < length && this.heap[rightChildIndex] < this.heap[smallestIndex]) {
39 smallestIndex = rightChildIndex;
40 }
41 if (smallestIndex === index) break;
42 [this.heap[index], this.heap[smallestIndex]] = [this.heap[smallestIndex], this.heap[index]];
43 index = smallestIndex;
44 }
45 }
46}