← Back to Algorithms, page 3

algorithms-0041 · Hard senior

Merge k sorted linked lists into one sorted list in O(N log k) time, where N is the total number of nodes.

Put the head of each list in a min-heap keyed by value. Repeatedly pop the smallest node, attach it to the output and push that node's successor. The heap never holds more than k nodes, so each of the N steps costs O(log k). Pairwise divide-and-conquer merging gives the same O(N log k) bound without a heap.

Full answer

Problem

Given k sorted linked lists, merge them into one sorted list by relinking nodes, and return its head.

Example: [1 -> 4 -> 5, 1 -> 3 -> 4, 2 -> 6] gives 1 -> 1 -> 2 -> 3 -> 4 -> 4 -> 5 -> 6.

Constraints: 0 <= k <= 10^4, total nodes N <= 10^4, any list may be empty.

Brute force

Collect all values, sort them and build a new list: O(N log N) time, O(N) extra space.

Merging lists one at a time into a growing result: the result is re-scanned each time, O(N x k) in total.

Optimal approach

  1. Push (node.val, i, node) for each non-empty list head. The index i breaks ties so Python never compares two ListNode objects (which would raise TypeError).
  2. Use a dummy head and a tail pointer.
  3. While the heap is not empty: pop the smallest, attach it, and push its next if it exists.

Alternative: divide and conquer. Merge lists in pairs (0 with 1, 2 with 3, ...), then merge the results, for log k rounds of O(N) work each. The code includes merge_two, the building block.

Why it works

The smallest remaining node overall must be the head of one of the remaining lists, because each list is sorted. The heap holds exactly those heads, so popping its minimum always gives the next node of the output. Pushing the successor keeps the heap equal to the set of current heads.

Complexity

O(N log k) time. O(k) extra space for the heap; output reuses the existing nodes.

Code

python
import heapq


class ListNode:
    def __init__(self, val, next=None):
        self.val = val
        self.next = next


def from_list(values):
    head = None
    for v in reversed(values):
        head = ListNode(v, head)
    return head


def to_list(head):
    out = []
    while head:
        out.append(head.val)
        head = head.next
    return out


def merge_two(a, b):
    """Merge two sorted lists by relinking nodes. O(len(a) + len(b))."""
    dummy = tail = ListNode(0)
    while a and b:
        if a.val <= b.val:          # <= keeps the merge stable
            tail.next, a = a, a.next
        else:
            tail.next, b = b, b.next
        tail = tail.next
    tail.next = a or b
    return dummy.next


def merge_k_lists(lists):
    """Merge k sorted lists with a min-heap of the current heads. O(N log k)."""
    heap = [(node.val, i, node) for i, node in enumerate(lists) if node]
    heapq.heapify(heap)              # i breaks ties so nodes are never compared
    dummy = tail = ListNode(0)
    while heap:
        _, i, node = heapq.heappop(heap)
        tail.next = node
        tail = node
        if node.next:
            heapq.heappush(heap, (node.next.val, i, node.next))
    return dummy.next


if __name__ == "__main__":
    assert to_list(merge_two(from_list([1, 2, 4]), from_list([1, 3, 4]))) == [1, 1, 2, 3, 4, 4]
    assert to_list(merge_two(None, from_list([0]))) == [0]
    lists = [from_list([1, 4, 5]), from_list([1, 3, 4]), from_list([2, 6])]
    assert to_list(merge_k_lists(lists)) == [1, 1, 2, 3, 4, 4, 5, 6]
    assert merge_k_lists([]) is None
    assert merge_k_lists([None, None]) is None
    assert to_list(merge_k_lists([from_list([-2]), None, from_list([-3, 9])])) == [-3, -2, 9]
    print("all tests passed")

Save as a41_merge_k_lists.py and run python3 a41_merge_k_lists.py. It prints all tests passed (Python 3.13.5).

Edge cases

Empty input list. All lists empty. A single list. Lists of very different lengths. Negative values. Equal values across lists (the tie-breaker index prevents comparing nodes).

Pattern

K-way merge with a heap. It is also used for external sorting of files too large for memory, merging sorted log files from many servers, and finding the smallest range covering k lists.

python
import heapq


class ListNode:
    def __init__(self, val, next=None):
        self.val = val
        self.next = next


def from_list(values):
    head = None
    for v in reversed(values):
        head = ListNode(v, head)
    return head


def to_list(head):
    out = []
    while head:
        out.append(head.val)
        head = head.next
    return out


def merge_two(a, b):
    """Merge two sorted lists by relinking nodes. O(len(a) + len(b))."""
    dummy = tail = ListNode(0)
    while a and b:
        if a.val <= b.val:          # <= keeps the merge stable
            tail.next, a = a, a.next
        else:
            tail.next, b = b, b.next
        tail = tail.next
    tail.next = a or b
    return dummy.next


def merge_k_lists(lists):
    """Merge k sorted lists with a min-heap of the current heads. O(N log k)."""
    heap = [(node.val, i, node) for i, node in enumerate(lists) if node]
    heapq.heapify(heap)              # i breaks ties so nodes are never compared
    dummy = tail = ListNode(0)
    while heap:
        _, i, node = heapq.heappop(heap)
        tail.next = node
        tail = node
        if node.next:
            heapq.heappush(heap, (node.next.val, i, node.next))
    return dummy.next


if __name__ == "__main__":
    assert to_list(merge_two(from_list([1, 2, 4]), from_list([1, 3, 4]))) == [1, 1, 2, 3, 4, 4]
    assert to_list(merge_two(None, from_list([0]))) == [0]
    lists = [from_list([1, 4, 5]), from_list([1, 3, 4]), from_list([2, 6])]
    assert to_list(merge_k_lists(lists)) == [1, 1, 2, 3, 4, 4, 5, 6]
    assert merge_k_lists([]) is None
    assert merge_k_lists([None, None]) is None
    assert to_list(merge_k_lists([from_list([-2]), None, from_list([-3, 9])])) == [-3, -2, 9]
    print("all tests passed")

heapq with (value, list index, node) tuples so nodes are never compared; merge_two is included for the divide-and-conquer version.

Complexity

Time: O(N log k). Space: O(k) for the heap. Sequential merging is O(N * k); divide and conquer matches the heap bound.

By level

Fresher: Gives the sort-everything approach, then explains the heap of heads and implements it. Should be able to merge two sorted lists with a dummy head.

Mid: Handles Python's comparison issue, analyses O(N log k) and presents divide and conquer. Adds a tie-breaker so nodes are never compared.

Senior: Applies k-way merge to external sorting and distributed log merging, and discusses memory, I/O and heap versus tournament tree trade-offs. Can compare heap and divide-and-conquer merging by memory use.

Key points

  • The next output node is the smallest current head
  • A heap of k heads gives O(log k) per step
  • Add a tie-breaker so nodes are not compared
  • Dummy head simplifies building the result
  • Divide and conquer is an equal alternative

Common mistakes

  • Pushing ListNode objects without a tie-breaker
  • Merging lists one by one and calling it optimal
  • Forgetting to push the successor
  • Dropping empty lists incorrectly or pushing None

Follow-ups

  • How would you merge k sorted files that do not fit in memory?
  • How do you find the smallest range that includes a number from each list?
  • When would divide and conquer beat the heap in practice?

Tips

  • Explain why the minimum is among the heads
  • Mention the tie-breaker issue in Python
  • State N and k separately in the complexity

Evaluation rubric

  • Correct heap-based merge
  • Correct complexity in N and k
  • Handles empty lists
  • Mentions an alternative