← Back

Min-Heap

heappriority-queuecomplete-tree
Press play to start
1class MinHeap {
2 private heap: number[] = []
3 insert(val: number): void {
4 this.heap.push(val)
5 this.bubbleUp(this.heap.length - 1)
6 }
7 private bubbleUp(i: number): void {
8 const p = Math.floor((i - 1) / 2)
9 if (i > 0 && this.heap[i] < this.heap[p]) {
10 [this.heap[i], this.heap[p]] = [this.heap[p], this.heap[i]]
11 this.bubbleUp(p)
12 }
13 }
14 extractMin(): number | undefined {
15 if (!this.heap.length) return undefined
16 const min = this.heap[0]
17 this.heap[0] = this.heap.pop()!
18 this.heapifyDown(0)
19 return min
20 }
21}
Step 1/0

Complexity

Best:O(1)
Average:O(log n)
Worst:O(log n)
Space:O(n)

Description

A complete binary tree where every parent node is smaller than its children. The root is always the minimum element.

When to use

Priority queues, Dijkstra's algorithm, heap sort, scheduling systems. O(log n) insert and O(1) min access.