ποΈ Heap (Priority Queue)
One-line summary: A complete binary tree satisfying the heap property β O(log n) insert and extract-min/max, the engine behind Top-K, median, K-way merge, and scheduling algorithms.
Diagramβ
Conceptβ
- Min-heap: parent β€ children β
peek()is minimum. - Max-heap: parent β₯ children β
peek()is maximum. - JavaScript has no native heap β simulate with sorted array or use
@datastructures-js/priority-queue.
Key operations: insert O(log n), extractMin/Max O(log n), peek O(1), heapify O(n).
Time & Space Complexityβ
| Operation | Time | Space |
|---|---|---|
| Insert | O(log n) | O(1) |
| Extract min/max | O(log n) | O(1) |
| Peek | O(1) | O(1) |
| Heapify | O(n) | O(1) |
| Top-K elements | O(n log k) | O(k) |
| K-way merge (n total, k lists) | O(n log k) | O(k) |
Common Patternsβ
Pattern 1 β Top-K Frequent (Min-Heap of size K)β
function topKFrequent(nums, k) {
const freq = new Map();
for (const n of nums) freq.set(n, (freq.get(n) || 0) + 1);
return [...freq.entries()]
.sort((a, b) => b[1] - a[1])
.slice(0, k)
.map(([num]) => num);
}
Pattern 2 β Two Heaps (Median from Stream)β
// maxHeap = lower half, minHeap = upper half
// Invariant: |maxHeap.size - minHeap.size| <= 1
// Median = maxHeap.top() or avg of both tops
Pattern 3 β K-way Mergeβ
// 1. Add first element from each list to min-heap with [value, listIdx, elemIdx]
// 2. Extract min β push to result β add next element from same list
// 3. Repeat until heap empty
Pitfallsβ
- JS has no native heap β off-the-shelf sort trick is O(n log n), not O(n log k)
- Rebalancing Two Heaps: ensure size diff β€ 1 after every insert
- K-way merge: track which list each heap element came from
Practice Problemsβ
Related Topicsβ
- Trees β heap is a complete binary tree
- Sorting β heapsort uses heap operations
- Graphs β Dijkstra uses min-heap
β Back to Home Β· Β© sparshjaswal