Merge k Sorted Lists

Pattern: K-way merge

hard

Keep a min heap of the current head of each list. Pop the smallest node, link it to the result, and push its next node. N nodes in total pass through a heap of at most k, so O(N log k).

The problem

Given an array of k sorted linked lists, merge them into one sorted list and return its head. Some lists may be empty, and the array itself may be empty.

Think first

  • Which node comes first in the result?
  • After it is used, which node replaces it as a candidate?
  • How do you avoid special cases at the start of the result?

Hints

    Brute force, and why it fails

    Merge the lists one by one into a growing result: O(N × k). Merging in pairs, round by round, is O(N log k) too.

    The key insight

    The heap holds one node per list, so each step finds the overall smallest in O(log k) and the nodes are relinked without copying.

    Dry run

    heap1 1 2

    lists 1→4→5, 1→3→4, 2→6. The heap holds 1, 1, 2.

    Step 1 of 3

    The plan

    heap = heads that are not null
    dummy = tail = new node
    while heap:
        node = pop; tail.next = node; tail = node
        if node.next: push node.next
    return dummy.next
    

    Complexity

    Time
    O(N log k)
    Space
    O(k)

    Each of the N nodes is pushed and popped once.

    Edge cases

    • No lists: null.
    • Only empty lists: null.
    • One list: itself.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public ListNode mergeKLists(ListNode[] lists) {
            PriorityQueue<ListNode> heap = new PriorityQueue<>((x, y) -> Integer.compare(x.val, y.val));
            for (ListNode head : lists) if (head != null) heap.add(head);   // the front of each list
            ListNode dummy = new ListNode(0), tail = dummy;
            while (!heap.isEmpty()) {
                ListNode node = heap.poll();        // the smallest front overall
                tail.next = node;
                tail = node;
                if (node.next != null) heap.add(node.next);   // its list's next node takes its place
            }
            return dummy.next;
        }
    }

    C++

    class Solution {
    public:
        struct ByVal {
            bool operator()(ListNode* a, ListNode* b) const { return a->val > b->val; }   // smallest on top
        };
    
        ListNode* mergeKLists(vector<ListNode*>& lists) {
            priority_queue<ListNode*, vector<ListNode*>, ByVal> heap;
            for (ListNode* head : lists) if (head != NULL) heap.push(head);   // the front of each list
            ListNode dummy(0);
            ListNode* tail = &dummy;
            while (!heap.empty()) {
                ListNode* node = heap.top();        // the smallest front overall
                heap.pop();
                tail->next = node;
                tail = node;
                if (node->next != NULL) heap.push(node->next);   // its list's next node takes its place
            }
            return dummy.next;
        }
    };

    Python

    import heapq
    from lib import ListNode
    
    
    class Solution:
        def mergeKLists(self, lists: list) -> object:
            heap = [(head.val, i, head) for i, head in enumerate(lists) if head]   # the front of each list
            heapq.heapify(heap)                     # i breaks ties, so nodes are never compared
            dummy = tail = ListNode(0)
            while heap:
                _, i, node = heapq.heappop(heap)    # the smallest front overall
                tail.next = tail = node
                if node.next:
                    heapq.heappush(heap, (node.next.val, i, node.next))   # its list's next node takes its place
            return dummy.next

    Common mistakes

    • Comparing nodes directly in Python's heapq; add an index as a tie-breaker.
    • Pushing a null next.

    Similar problems