33/39
Part 7 of 7 · Follow-upsLearn

How do you merge k sorted lists?

Merging them into the result one at a time walks the growing result again for every list: O(N k) for N nodes in all.

A heap keeps its smallest item on top, and adding or removing an item in a heap of k items takes O(log k). Python's is the heapq module. A heap of the k front nodes gives O(N log k) in all:

import heapq


def merge_k(heads):
    heap = [(head.val, i, head) for i, head in enumerate(heads) if head is not None]
    heapq.heapify(heap)
    dummy = tail = Node(None)
    while heap:
        _, i, node = heap[0]
        tail.next = node
        tail = node
        if node.next is not None:
            heapq.heapreplace(heap, (node.next.val, i, node.next))
        else:
            heapq.heappop(heap)
    return dummy.next

The list number i sits between the value and the node. So two equal values never fall through to comparing two Node objects, which would raise TypeError.

Merging in pairs, the lists two at a time and then the results two at a time, is also O(N log k):

def merge_one_at_a_time(heads):
    out = None
    for head in heads:
        out = merge_two(out, head)
    return out


def merge_in_pairs(heads):
    heads = list(heads)
    if not heads:
        return None
    while len(heads) > 1:
        heads = [merge_two(heads[i], heads[i + 1] if i + 1 < len(heads) else None)
                 for i in range(0, len(heads), 2)]
    return heads[0]

On sorted lists of random integers, median of 3 runs:

ListsHeapOne at a timeIn pairs
10 of 10,00017.4 ms23.9 ms17.7 ms
100 of 1,00025.5 ms207.2 ms36.4 ms
1,000 of 10037.0 ms2,252.0 ms56.1 ms