SDE & MLE Prep

23. Merge k Sorted Lists

Problem

Merge k sorted linked lists into one sorted list and return its head.

Example: [1→4→5, 1→3→4, 2→6] → 1→1→2→3→4→4→5→6

Constraints: k ≤ 10⁴; at most 10⁴ nodes in total.

Min-heap of the current head of each list; pop the smallest, push its successor. (Or pairwise merge, like merge sort.)

Complexity: O(N log k) for N total nodes.

class Solution:
    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
        heap = [(node.val, i, node) for i, node in enumerate(lists) if node]
        heapify(heap)
        dummy = tail = ListNode()
        while heap:
            _, i, node = heappop(heap)      # i breaks ties (nodes aren't comparable)
            tail.next = tail = node
            if node.next:
                heappush(heap, (node.next.val, i, node.next))
        return dummy.next