Heap / Priority Queue
Signal: "k largest / smallest / closest / most frequent", "merge k sorted…", "always process the cheapest/earliest next", scheduling, or a running median over a stream.
Core idea: a binary heap keeps the minimum (or maximum) at the root, with O(log n) push/pop and O(1) peek. It's a complete binary tree stored in an array: the children of i are 2i+1 and 2i+2.
Patterns
| Goal | Heap | Size |
|---|---|---|
| k largest elements | min-heap: pop the smallest when size > k | k → O(n log k) |
| k smallest / closest | max-heap (negate values in Python) | k |
| Merge k sorted lists | min-heap of the current heads | k → O(N log k) |
| Running median | max-heap (lower half) + min-heap (upper half) | balanced |
| Greedy scheduling | max-heap by remaining count/priority | tasks |
python
import heapq # Python's heapq is a MIN-heap
h = []
heapq.heappush(h, 5); heapq.heappush(h, 1)
heapq.heappop(h) # 1
heapq.heappush(h, -x) # max-heap trick: store negatives
heapq.nlargest(3, nums) # handy built-insJavaScript has no built-in heap, so in interviews either write a small one (below) or say you'd use a library. Solutions in this section include a compact MinHeap.
javascript
class MinHeap {
constructor(cmp = (a, b) => a - b) { this.a = []; this.cmp = cmp; }
get size() { return this.a.length; }
peek() { return this.a[0]; }
push(x) { const a = this.a; a.push(x); let i = a.length - 1;
while (i > 0) { const p = (i - 1) >> 1; if (this.cmp(a[i], a[p]) >= 0) break; [a[i], a[p]] = [a[p], a[i]]; i = p; } }
pop() { const a = this.a, top = a[0], last = a.pop();
if (a.length) { a[0] = last; let i = 0;
for (;;) { const l = 2 * i + 1, r = l + 1; let m = i;
if (l < a.length && this.cmp(a[l], a[m]) < 0) m = l;
if (r < a.length && this.cmp(a[r], a[m]) < 0) m = r;
if (m === i) break; [a[i], a[m]] = [a[m], a[i]]; i = m; } }
return top; }
}