~/problems

Problems

Basics first, then the classics, then company-style assessments. Every problem has tests you run right here; multi-level ones unlock as you go. See the roadmap.

Heaps

Heaps and priority queues

heapq: top-k, k-way merge, two heaps for a running median.

Notes

Recognise it when: you need top-k, the k-th largest, merging k sorted streams, repeatedly taking the smallest or largest, or a running median.

heapq.nlargest(k, cnt, key=cnt.get)           # top-k frequent
h = []                                        # size-k min-heap for k-th largest
for x in nums:
    heapq.heappush(h, x)
    if len(h) > k: heapq.heappop(h)

# k-way merge: (value, list_index, element_index)

Running median: a max-heap lo (stored negated) and a min-heap hi. Push to lo, move lo's max to hi, and rebalance so len(lo) >= len(hi).

Gotchas: heapq is a min-heap only, so negate for max. Add a tie-breaker to tuples so Python never compares the objects themselves. Building a heap with heapify is O(n).

15 problems

Interview roadmap

Heaps Top-k, merging streams, scheduling by time.

Heaps and priority queues guide

esc