Skip to content

Merge k Sorted Lists

Merge k sorted linked lists into one by always taking the smallest front node from a min-heap.

HardHeaps and Top K
Solve on LeetCode

The problem

You get an array of k linked lists, each sorted in ascending order. Merge them all into one sorted linked list and return its head. Some of the lists may be empty, and so may the array itself.

Input lists = [[2, 6, 9], [1, 7], [3, 4, 10]]

Output [1, 2, 3, 4, 6, 7, 9, 10]

The heap holds the front node of each list, so the smallest remaining value is always on top.

Input lists = [[], [5], []]

Output [5]

Empty lists add nothing; the result is just the 5.

Key constraint: Up to 10,000 lists with up to 10,000 nodes in total, so merging the lists into the result one at a time can take O(N * k) time.

How to spot the pattern

  • You have k sorted sources and need one sorted output.
  • At every step you need the smallest of k front items, which a min-heap gives in O(log k).

The idea

The next node of the merged list is always the smallest among the current front nodes of the k lists. Keep those front nodes in a min-heap ordered by value. Pop the smallest, attach it to the result and push its successor from the same list, so the heap never holds more than one node per list.

Brute force: Collect every value, sort them and build a new list, which costs O(N log N) time and O(N) extra space for N nodes in total.

Step by step

  1. 1Put the head of every non-empty list into a min-heap ordered by node value.
  2. 2Create a dummy node and a tail pointer that starts at it.
  3. 3While the heap is not empty, pop the smallest node and attach it after tail.
  4. 4If the popped node has a next, push that node into the heap.
  5. 5Return dummy.next.

See the pattern move

The heaps and top k pattern on a small example. Step through it, or press play.

Code

import heapq


class Solution:
    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
        # Entries are (value, list index, node); the index breaks ties, because
        # Python can't compare two ListNode objects.
        heap = [(node.val, i, node) for i, node in enumerate(lists) if node]
        heapq.heapify(heap)
        dummy = ListNode()
        tail = dummy
        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

Complexity

Time

O(N log k)

Space

O(k)

N is the total number of nodes: each one is pushed and popped once, on a heap that never holds more than k nodes.

Watch out for

  • In Python, pushing nodes into heapq as they are: when two values tie, Python tries to compare the nodes and fails, so add the list index as a tie-breaker.
  • Pushing the null head of an empty list into the heap.
  • Pushing every node at the start, which makes the heap hold N nodes instead of k.

Follow-up questions

Can you do it without a heap?

Merge the lists in pairs, like the merge step of merge sort: merge list 0 with 1, 2 with 3 and so on, then repeat on the results. There are about log k rounds of O(N) work each, so it is also O(N log k), with O(1) extra space.

Why not merge the lists into the result one by one?

The result keeps growing, so its early nodes are walked again in every merge; over k merges that adds up to O(N * k).

In Hinglish

Har list ka pehla node min-heap mein daalo. Sabse chhota nikaalo, result mein jodo, aur usi list ka agla node heap mein daal do.

Related problems