Heap and priority queue in JavaScript
Custom min-heap
class MinHeap {
constructor() {
this.heap = [];
}
push(val) {
this.heap.push(val);
this.bubbleUp(this.heap.length - 1);
}
bubbleUp(index) {
while (index > 0) {
const parent = Math.floor((index - 1) / 2);
if (this.heap[parent] <= this.heap[index]) break;
[this.heap[parent], this.heap[index]] = [this.heap[index], this.heap[parent]];
index = parent;
}
}
}Problems to practice
- Kth largest element
- Top K frequent elements
- Merge K sorted lists
Can you explain it without the notes?
Heap and priority queue in JavaScript
Use your own words. Explain an example and one limitation before checking the explanation.
Check your explanation
Custom min-heap
Turn this concept into a clear answer.
Practice this conceptAdapted from 16_DSA_JAVASCRIPT.md · “8. Heap and priority queue in JavaScript”. Examples are study fragments; framework behavior can depend on your version.