Module 4 · Drill 1 · heap reps
Three problems that push the heap pattern in different directions. Python only — JS doesn't ship a heap, and for these we want the real-deal heap experience.
Note: tests above expect a specific order. If your function returns the right set in a different order, sort the result before returning.
import heapq
from collections import Counter
def top_k_frequent(nums, k):
counts = Counter(nums)
# min-heap of (frequency, value), capped at size k
heap = []
for val, freq in counts.items():
if len(heap) < k:
heapq.heappush(heap, (freq, val))
elif freq > heap[0][0]:
heapq.heapreplace(heap, (freq, val))
return sorted([v for _, v in heap])
function topKFrequent(nums, k) {
const counts = new Map();
for (const x of nums) counts.set(x, (counts.get(x) || 0) + 1);
return [...counts.entries()]
.sort((a, b) => b[1] - a[1])
.slice(0, k)
.map(([v]) => v)
.sort((a, b) => a - b);
}
function topKFrequent(nums: number[], k: number): number[] {
const counts = new Map<number, number>();
for (const x of nums) counts.set(x, (counts.get(x) || 0) + 1);
return [...counts.entries()]
.sort((a, b) => b[1] - a[1])
.slice(0, k)
.map(([v]) => v)
.sort((a, b) => a - b);
}
tools/reference.html#heap) to recover O(n log k) in production.
import heapq
def merge_k(lists):
out = []
heap = []
# seed: first element of each non-empty list
for li, lst in enumerate(lists):
if lst:
heapq.heappush(heap, (lst[0], li, 0))
while heap:
val, li, ei = heapq.heappop(heap)
out.append(val)
if ei + 1 < len(lists[li]):
heapq.heappush(heap, (lists[li][ei + 1], li, ei + 1))
return out
function mergeK(lists) {
if (!lists.length) return [];
function merge(a, b) {
const out = []; let i = 0, j = 0;
while (i < a.length && j < b.length) out.push(a[i] <= b[j] ? a[i++] : b[j++]);
return out.concat(a.slice(i), b.slice(j));
}
let step = 1;
while (step < lists.length) {
for (let i = 0; i + step < lists.length; i += step * 2) {
lists[i] = merge(lists[i], lists[i + step]);
}
step *= 2;
}
return lists[0] || [];
}
function mergeK(lists: number[][]): number[] {
if (!lists.length) return [];
function merge(a: number[], b: number[]): number[] {
const out: number[] = []; let i = 0, j = 0;
while (i < a.length && j < b.length) out.push(a[i] <= b[j] ? a[i++] : b[j++]);
return out.concat(a.slice(i), b.slice(j));
}
let step = 1;
while (step < lists.length) {
for (let i = 0; i + step < lists.length; i += step * 2) {
lists[i] = merge(lists[i], lists[i + step]);
}
step *= 2;
}
return lists[0] || [];
}
import heapq
class MedianFinder:
def __init__(self):
self.lo = [] # max-heap (push -x)
self.hi = [] # min-heap
def add(self, x):
# default: push to lo
heapq.heappush(self.lo, -x)
# ensure lo's top <= hi's top
if self.hi and -self.lo[0] > self.hi[0]:
heapq.heappush(self.hi, -heapq.heappop(self.lo))
# rebalance sizes (lo can be at most 1 larger than hi)
if len(self.lo) > len(self.hi) + 1:
heapq.heappush(self.hi, -heapq.heappop(self.lo))
elif len(self.hi) > len(self.lo):
heapq.heappush(self.lo, -heapq.heappop(self.hi))
def median(self):
if len(self.lo) > len(self.hi):
return -self.lo[0]
return (-self.lo[0] + self.hi[0]) / 2
def run(ops):
mf = MedianFinder()
out = []
for op in ops:
if op[0] == 'add': mf.add(op[1])
elif op[0] == 'median': out.append(mf.median())
return out
// JS/TS without a heap library — sorted-insert keeps O(1) median lookup
// at the cost of O(n) add. For real production code you'd build the
// MinHeap/MaxHeap (see tools/reference.html#heap) and recover O(log n) add.
class MedianFinder {
constructor() { this.a = []; }
add(x) {
let lo = 0, hi = this.a.length;
while (lo < hi) { const m = (lo + hi) >> 1; if (this.a[m] < x) lo = m + 1; else hi = m; }
this.a.splice(lo, 0, x);
}
median() {
const n = this.a.length;
return n % 2 ? this.a[n >> 1] : (this.a[n / 2 - 1] + this.a[n / 2]) / 2;
}
}
function run(ops) {
const mf = new MedianFinder();
const out = [];
for (const op of ops) {
if (op[0] === 'add') mf.add(op[1]);
else if (op[0] === 'median') out.push(mf.median());
}
return out;
}
class MedianFinder {
private a: number[] = [];
add(x: number): void {
let lo = 0, hi = this.a.length;
while (lo < hi) { const m = (lo + hi) >> 1; if (this.a[m] < x) lo = m + 1; else hi = m; }
this.a.splice(lo, 0, x);
}
median(): number {
const n = this.a.length;
return n % 2 ? this.a[n >> 1] : (this.a[n / 2 - 1] + this.a[n / 2]) / 2;
}
}
function run(ops: any[]): number[] {
const mf = new MedianFinder();
const out: number[] = [];
for (const op of ops) {
if (op[0] === 'add') mf.add(op[1]);
else if (op[0] === 'median') out.push(mf.median());
}
return out;
}