Skip to content
Gold 7 min read · Algorithms 3 practice problems ↓

Heaps, top-k and k-way merges

"Top 10 of a million", "merge these sorted files", "always process the most urgent job next": all of these need the smallest or largest item again and again, but never the whole list sorted. A heap does exactly that, cheaply. This lesson shows how heapq works and the patterns interviews ask for.

Foundations · Python for data engineers · Gold · Algorithms interviewers ask, lesson 1 of 3

Read first: Sorting with key functions (skip if you know it)

In plain words first

A hospital waiting room does not sort every patient perfectly; it only needs to know who is most urgent right now. When that patient is seen, the next most urgent moves to the front. Nobody else needs to be in exact order.

A heap is that waiting room: the smallest (or most urgent) item is always at the front, and adding or removing one is quick, because the rest is only roughly arranged.

A heap always knows its smallest item

A min-heap keeps its smallest item at index 0. Adding an item or removing the smallest costs O(log n); looking at the smallest is O(1). It does not keep everything sorted, which is why it is cheaper than sorting when you only ever need "the next smallest". Python's heapq works on a plain list.

Python · the soonest delivery first
import heapq

etas = []
for minutes, order_id in [(25, "o1"), (8, "o2"), (40, "o3"), (15, "o4")]:
    heapq.heappush(etas, (minutes, order_id))

print("soonest, without removing it:", etas[0])
while etas:
    minutes, order_id = heapq.heappop(etas)
    print(minutes, "min:", order_id)

Output from a real run

soonest, without removing it: (8, 'o2')
8 min: o2
15 min: o4
25 min: o1
40 min: o3
OperationCost
heappush, heappopO(log n)
Peek the smallest: h[0]O(1)
heapify(list)O(n), in place
nsmallest(k, it) / nlargest(k, it)O(n log k)

Top-k without sorting everything

For the k best of n items, keep a heap of size k: push each item, and when the heap grows past k, pop the smallest. Memory stays O(k) and time is O(n log k), much better than O(n log n) when k is small, and it works on a stream. heapq.nlargest(k, it, key=...) does exactly this.

Python · the three biggest orders of a stream, with a bounded heap
import heapq

amounts = [120, 950, 40, 610, 300, 780, 55]
best = []
for a in amounts:
    heapq.heappush(best, a)
    if len(best) > 3:
        heapq.heappop(best)
print("bounded heap:", sorted(best, reverse=True))
print("nlargest:    ", heapq.nlargest(3, amounts))

Output from a real run

bounded heap: [950, 780, 610]
nlargest:     [950, 780, 610]
Tip: heapq is a min-heap only. For a max-heap, push negated numbers, or for top-k keep a min-heap of the best k seen so far, as above: its root is the weakest of the winners.

Tuples and tie-breaking

Heap items are compared with <, and tuplestuple: An ordered, immutable sequence like ("Pune", 2026). Because it cannot change, it can be a dict key; use it for small fixed records. Learn more → compare element by element. When two first elements tie, Python compares the second ones, and if those are dicts or custom objects it raises TypeError. Insert a unique, comparable tie-breaker, such as a counter or an index: (priority, seq, item). The tie-breaker also makes the order of equal priorities deterministic.

Python · equal priorities, uncomparable payloads
import heapq
import itertools

seq = itertools.count()  # 0, 1, 2, ... in the order jobs arrive
jobs = []
for prio, job in [(1, {"id": "a"}), (1, {"id": "b"}), (0, {"id": "c"})]:
    heapq.heappush(jobs, (prio, next(seq), job))

while jobs:
    prio, arrived, job = heapq.heappop(jobs)
    print("priority", prio, "arrived", arrived, "job", job["id"])

Output from a real run

priority 0 arrived 2 job c
priority 1 arrived 0 job a
priority 1 arrived 1 job b

k-way merge

Merging k sorted inputs (files from an external sort, per-partition outputs, time-ordered streams) needs only one pending item per input on a heap: pop the smallest, emit it, push the next item from the same input. That is O(N log k) for N items and O(k) memory. heapq.merge implements it lazilylazy: Computed only when asked for, one item at a time, instead of all at once up front. Saves memory on large data. Learn more →, assuming its inputs are sorted.

Python · three sorted feeds into one
import heapq

app = [1, 4, 9]
web = [2, 3, 10]
partner = [5]
print("heapq.merge:", list(heapq.merge(app, web, partner)))

pending = [(feed[0], i, 0) for i, feed in enumerate([app, web, partner])]
heapq.heapify(pending)
feeds, out = [app, web, partner], []
while pending:
    value, i, pos = heapq.heappop(pending)
    out.append(value)
    if pos + 1 < len(feeds[i]):
        heapq.heappush(pending, (feeds[i][pos + 1], i, pos + 1))
print("by hand:    ", out)

Output from a real run

heapq.merge: [1, 2, 3, 4, 5, 9, 10]
by hand:     [1, 2, 3, 4, 5, 9, 10]

Linked lists: merging by relinking

Interview questions sometimes give the sorted inputs as linked lists instead of Python lists. A linked list is a chain of small objects, often called nodes: each holds one value and a next link to the following node, and the last one links to None. You hold only the first node, the head. There is no [i]: to reach the fifth value you follow four links.

Merging linked lists does not copy values into a new list. It relinks the existing nodes: point the end of the merged chain at the smaller front node, and move on. A placeholder node in front of the result means the first node needs no special case.

Python · two sorted delivery routes, relinked into one
class Stop:
    """One stop on a route: a minute and a link to the next stop."""

    def __init__(self, minute, next=None):
        self.minute = minute
        self.next = next


def build(minutes):
    head = None
    for minute in reversed(minutes):
        head = Stop(minute, head)  # the new stop points at the old head
    return head


def minutes_of(stop):
    out = []
    while stop:  # follow the links until there is no next stop
        out.append(stop.minute)
        stop = stop.next
    return out


def merge_routes(a, b):
    front = end = Stop(None)  # placeholder: the real head is front.next
    while a and b:
        if a.minute <= b.minute:
            end.next, a = a, a.next
        else:
            end.next, b = b, b.next
        end = end.next
    end.next = a or b  # what is left is already sorted
    return front.next


first = build([5, 20, 40])
merged = merge_routes(first, build([10, 30]))
print(minutes_of(merged))
print("same first node, relinked:", merged is first)

Output from a real run

[5, 10, 20, 30, 40]
same first node, relinked: True

With k linked lists, put each list's current node on a heap instead of comparing two by hand, exactly like the k-way merge above: pop the smallest, link it to the end, and push its next node if there is one. Nodes usually cannot be compared with <, so the heap tuple needs the tie-breaker from the previous section before the node.

Common mistakes

  • Sorting everything to take the top 10 — O(n log n) and all in memory. Use a size-k heap or nlargest.
  • (priority, dict) tuples — Ties compare the dicts and raise TypeError. Add a counter.
  • Reading h[1] as "the second smallest" — A heap is only partially ordered. Pop to get items in order.
  • Pushing (value, node) for linked lists — Equal values make Python compare the nodes, which raises TypeError. Push (value, index, node).

Key takeaways

  • A heap gives the smallest item in O(1), push/pop in O(log n).
  • Top-k: a size-k heap, O(n log k), O(k) memory.
  • Add a unique tie-breaker to heap tuples.
  • k-way merge: one pending item per input, O(N log k).
  • Linked lists are merged by relinking nodes, with a placeholder node in front.

Interview prep

THE QUESTION

"Find the 10 most frequent search terms in a log of a billion lines."

Count with a dict (or Counter) in one streaming pass; then select the top 10 with a size-10 min-heap over the counts, O(d log 10) for d distinct terms, instead of sorting all d. If d itself is too large for memory, partition terms by hash into files, count each partition, take each partition's top 10 and merge those, which is the map-reduce version Spark would run.

Avoid: "I would sort the list and take the first k". Correct, but O(n log n) and all in memory; a size-k heap is O(n log k) and works on a stream.

Follow-ups · answer out loud, then open

Follow-up"Python only has a min-heap. How do you get the largest items?"
Push negated numbers to simulate a max-heap, or for top-k keep a min-heap of size k: its root is the smallest of the current winners, so each new item only has to beat the root. heapq.nlargest does that.
Scenario"Merge 200 sorted files of events into one sorted file, without loading them."
A k-way merge: open every file, push each file's first record with its file index on a heap, then repeatedly pop the smallest, write it, and push the next record from the same file. heapq.merge does it lazily. O(N log 200) time, one pending record per file in memory.
Trap"heap[1] is the second smallest item."
A heap is only partially ordered: the second smallest is one of heap[1] or heap[2], and deeper items are not sorted. Pop to get items in order.

Check yourself

3 questions

Cost of heapq.heappop on n items?

Show the answer

O(log n). The heap re-balances along one root-to-leaf path.

Top 5 of a million numbers with heapq.nlargest is about...

Show the answer

O(n log 5). Each item may touch a heap of size 5.

Why push (prio, counter, item) instead of (prio, item)?

Show the answer

Ties never compare the items. The unique counter decides ties before the items are reached.

Practise this

Problems that use this, graded on hidden tests

Keep going

Up next · Algorithms interviewers ask · lesson 2 of 3 · 5 min read
Sliding windows, sweeps and binary search
O(n) windows, sort-then-sweep for intervals, and bisect for as-of lookups.

Related lessons

Previous: Dunder methods and abstract classes

Primary sources: heapq