Merge K Sorted Lists

Merge k sorted linked lists into one sorted list.

Pattern

Divide and Conquer / Heap

This problem follows the Divide and Conquer / Heap pattern, commonly found in the Linked List category. Recognizing this pattern is key to solving it efficiently in an interview setting.

Approach

How to Solve It

Use a min-heap to always pick the smallest head. Or merge lists pairwise.

Key Insight

The heap always has at most k elements (one per list), so each push/pop is O(log k) — total is O(n log k) for all n nodes.

Step-by-step

  1. 1Use a min-heap initialized with the head of each list
  2. 2Pop the smallest node from the heap
  3. 3Append it to the result list
  4. 4If the popped node has a next, push it into the heap
  5. 5Repeat until the heap is empty

Pseudocode

heap = []
for i, l in enumerate(lists):
    if l: heappush(heap, (l.val, i, l))
dummy = ListNode(0)
curr = dummy
while heap:
    val, i, node = heappop(heap)
    curr.next = node
    curr = curr.next
    if node.next:
        heappush(heap, (node.next.val, i, node.next))
return dummy.next
Complexity Analysis

Time Complexity

O(n log k)

Space Complexity

O(k)
More Linked List Problems

Master this pattern with YeetCode

Practice Merge K Sorted Lists and similar Linked List problems with flashcards. Build pattern recognition through active recall.

Practice this problem