Skip to contentKEEP THE CRAFTTHE SANCTUARY

K-way Merge

Keep one current head per nonempty sorted source in a min-heap. Emitting the smallest head and advancing only its source produces a sorted prefix without flattening all inputs first.

2 practice exercises3 interview problems

Recognize it when Several individually sorted sequences must be combined in global order.

Checking your account…

K-way Merge Code Labs

Use the Order Already Present in Each Source

Flattening every input and sorting again ignores useful source order. If each source is sorted, its first unconsumed value is no greater than any later value in that source. Therefore the next global minimum must be one of the visible heads. This proof requires sorted sources; a heap alone cannot reveal a smaller value hidden behind an unsorted head.

Give Each Frontier a Source and a Position

The Labs store numeric triples (value,source,position). Source identifies which list advances, while position identifies its next item. Those numeric fields also break equal-value ties deterministically. Empty sources contribute no head, and an exhausted source disappears from the heap.

Trace K-Way Heap Frontiers

Reference
import heapq

def merge_frontier_trace(sources):
    heap=[]; trace=[]
    for source,values in enumerate(sources):
        if values: heapq.heappush(heap,(values[0],source,0))
    while heap:
        trace.append([list(item) for item in sorted(heap)])
        value,source,position=heapq.heappop(heap)
        if position+1<len(sources[source]): heapq.heappush(heap,(sources[source][position+1],source,position+1))
    return trace
Practice

Implement merge_frontier_trace(sources). Return sorted heap triples [value,source,position] before each winner is removed. Every source is an indexable list sorted in nondecreasing order; empty sources are allowed.

Public tests

  • Keep one candidate per source

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Trace K-Way Heap Frontiers

import heapq

def merge_frontier_trace(sources):
    heap=[]; trace=[]
    for source,values in enumerate(sources):
        if values: heapq.heappush(heap,(values[0],source,0))
    while heap:
        trace.append([list(item) for item in sorted(heap)])
        value,source,position=heapq.heappop(heap)
        if position+1<len(sources[source]): heapq.heappush(heap,(sources[source][position+1],source,position+1))
    return trace

Tie-Break Equal Heads and Advance One Source

The existing trace on [[2, 6], [], [2, 5]] skips source 1 and breaks equal head values by source index. Snapshots are taken before each pop.

Step Executed statement State Why
Seed nonempty heads if values: heapq.heappush(heap,(values[0],source,0)) heap heads=(2,0,0) and (2,2,0) The empty source has no valid index zero.
First snapshot trace.append([list(item) for item in sorted(heap)]) [[2,0,0],[2,2,0]] Sorting the numeric triples shows deterministic source ownership.
Pop source 0 value,source,position=heapq.heappop(heap) winner=(2,0,0) Equal values are ordered by their source field.
Expose source 0 successor if position+1<len(sources[source]): heapq.heappush(heap,(sources[source][position+1],source,position+1)) next snapshot=[[2,2,0],[6,0,1]] Only source 0 advanced; source 2 still owns its original head.
Advance source 2 value,source,position=heapq.heappop(heap); heapq.heappush(heap,(sources[source][position+1],source,position+1)) after pushing 5: snapshot=[[5,2,1],[6,0,1]] Source 2 now exposes its second sorted value.
Exhaust source 2 trace.append([list(item) for item in sorted(heap)]) final snapshot=[[6,0,1]] After 5 is emitted there is no successor from source 2.
Return return trace four pre-pop frontier snapshots Each output item had one owning source and position.
Print Output
print(merge_frontier_trace([[2, 6], [], [2, 5]])) [[[2, 0, 0], [2, 2, 0]], [[2, 2, 0], [6, 0, 1]], [[5, 2, 1], [6, 0, 1]], [[6, 0, 1]]]

Advance Only the Source That Won

After a pop, every other source head remains its first unconsumed item. Push only the winning source’s successor if one exists. This preserves one frontier per unfinished source and keeps duplicate values as separate output items. The final Lab materializes the complete sorted result without mutating source lists.

Merge Sorted Sources

Reference
import heapq

def merge_sorted_sources(sources):
    heap=[]; result=[]
    for source,values in enumerate(sources):
        if values: heapq.heappush(heap,(values[0],source,0))
    while heap:
        value,source,position=heapq.heappop(heap); result.append(value)
        if position+1<len(sources[source]): heapq.heappush(heap,(sources[source][position+1],source,position+1))
    return result
Practice

Implement merge_sorted_sources(sources). Return one sorted list without mutating sources. Every source is an indexable list sorted in nondecreasing order; empty sources are allowed.

Public tests

  • Advance only the winning source

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Merge Sorted Sources

import heapq

def merge_sorted_sources(sources):
    heap=[]; result=[]
    for source,values in enumerate(sources):
        if values: heapq.heappush(heap,(values[0],source,0))
    while heap:
        value,source,position=heapq.heappop(heap); result.append(value)
        if position+1<len(sources[source]): heapq.heappush(heap,(sources[source][position+1],source,position+1))
    return result

Separate a Frontier Algorithm from its Diagnostic View

Scanning k sources and merging N values costs O(k+N log(m+1)) with m nonempty sources and O(m) heap space, plus O(N) result storage. The trace sorts and copies up to m triples before every pop, so its observation cost can be much larger. The standard heapq.merge returns a lazy iterator for already sorted iterables; the explicit Labs instead use list indexing so they can show source positions.

Explain Source Ownership in an Interview

Explain why an unseen item cannot beat its own source head, then why a pop changes only one frontier. Check an empty source and equal values from two sources. Concatenate-and-sort is simpler for small unsorted inputs; frontier merging is useful when sorted order can be reused or output can be produced incrementally. A requested kth value may stop early, while these Labs deliberately return the complete result or trace.

Template To Memorize

Learn this shape by heart; most problems in this family change only one or two lines of it.

Merge k sorted lists with a heap

Seed the heads, pop the smallest, push its next.

You merge several sorted sequences, or repeatedly need the smallest among k candidates.

Trigger words

  • merge k sorted
  • k sorted lists
  • k-th smallest in sorted matrix
  • news feed
  • smallest of k heads
import heapq

def merge_sorted(lists):
    heap = []
    for i, values in enumerate(lists):
        if values:
            heapq.heappush(heap, (values[0], i, 0))     # (value, list index, position)
    merged = []
    while heap:
        value, i, j = heapq.heappop(heap)
        merged.append(value)
        if j + 1 < len(lists[i]):
            heapq.heappush(heap, (lists[i][j + 1], i, j + 1))
    return merged

Spot it when

  • 'Merge k sorted lists'.
  • 'k-th smallest in a sorted matrix'.

Remember

  • The list index in the tuple breaks ties, so Python never compares the items themselves.
  • Each item is pushed and popped once: O(N log k).

How problems bend it

  • Linked lists: Push (node.val, i, node) and push node.next after popping.
  • Sorted matrix: Treat every row as a list and stop after k pops.

Python Version Note

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Merge N values from k sorted sourcesO(k + N log(m + 1))O(k + N log(m + 1))The code scans all k sources and uses at most m heap entries; every one of N output values is popped once.

Space

O(m) heap frontier plus O(N) materialized result, where m is the number of nonempty sources.

Assumptions

  • The trace sorts and copies the heap before each pop, adding O(N m log(m+1)) worst-case time and O(Nm) snapshot storage. Inputs are sorted indexable lists, not arbitrary iterators.
  • Python numeric tuple fields break equal-value ties deterministically by source and position, avoiding comparison of nonorderable payload objects.

Invariants Worth Saying Aloud

  1. The heap holds at most one first-unconsumed value from every nonempty unfinished source.
  2. The emitted result is a sorted prefix of all values; the next global minimum is one of the current source heads.

When To Use Or Avoid K-way Merge

Use It When

  • Merge sorted indexable lists while preserving inputs and retaining duplicate values.
  • Stop a frontier-based merge early for a requested rank after defining whether duplicates count.

Choose Another Tool When

  • Sort first or flatten and sort when sources are unsorted; heap frontiers cannot see hidden smaller successors.
  • Use heapq.merge for ordinary sorted iterables when source-position tracing is unnecessary; it consumes iterators as it produces values.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Seeding an empty source

An empty list has no first head, so unconditionally reading row[0] raises IndexError before merging can begin.

Prevent it: Seed only nonempty sources.

Avoid

heads = [(row[0],source,0) for source,row in enumerate(sources)]

Use instead

heads = [(row[0],source,0) for source,row in enumerate(sources) if row]

Advancing a different source

After source 0 emits 2 from [2, 6], exposing source 1's successor 5 hides the required next source-0 value 6 and duplicates another source's progress.

Prevent it: Use the popped source and position to expose its own successor.

Avoid

successor = sources[1][position+1]

Use instead

successor = sources[source][position+1]

Using nonorderable payloads to break a value tie

When equal priorities are followed by dict payloads, heap tuple comparison reaches the dictionaries and raises TypeError.

Prevent it: Put a unique numeric source or sequence tie-breaker before any nonorderable payload.

Avoid

heapq.heappush(heap,(2,{"source":0}))
heapq.heappush(heap,(2,{"source":1}))

Use instead

heapq.heappush(heap,(2,0,{"source":0}))
heapq.heappush(heap,(2,1,{"source":1}))

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.