sagelearnai

Merge k Sorted Lists

Difficulty: Hard · Pattern: Linked List · LeetCode #23

You're given an array of k linked lists, each sorted ascending. Merge them into one sorted linked list and return its head.

Examples

text
lists = [[1, 4, 5], [1, 3, 4], [2, 6]]   →  1 → 1 → 2 → 3 → 4 → 4 → 5 → 6
lists = []                               →  (empty)
lists = [[], [7]]                        →  7

Hints

  1. At every step, the next node in the output is the smallest among the k current heads.
  2. A min-heap finds that in O(log k).
  3. Alternative: merge lists pairwise (divide and conquer), also O(N log k).

Approach

Push the head of every non-empty list into a min-heap keyed by value (with a tiebreaker index in Python, since nodes aren't comparable). Repeatedly pop the smallest node, append it to the output (using a dummy head), and push that node's next if present. With N total nodes, each push/pop is O(log k): O(N log k) overall.

Complexity

Time: O(N log k). Space: O(k) for the heap.

Python solution
import heapq

def mergeKLists(lists):
    h = [(node.val, i, node) for i, node in enumerate(lists) if node]
    heapq.heapify(h)
    dummy = tail = ListNode()
    while h:
        val, i, node = heapq.heappop(h)
        tail.next = node
        tail = node
        if node.next:
            heapq.heappush(h, (node.next.val, i, node.next))
    return dummy.next
JavaScript solution
class MinHeap {
  constructor(cmp = (a, b) => a - b) { this.a = []; this.cmp = cmp; }
  get size() { return this.a.length; }
  peek() { return this.a[0]; }
  push(x) { const a = this.a; a.push(x); let i = a.length - 1;
    while (i > 0) { const p = (i - 1) >> 1; if (this.cmp(a[i], a[p]) >= 0) break; [a[i], a[p]] = [a[p], a[i]]; i = p; } }
  pop() { const a = this.a, top = a[0], last = a.pop();
    if (a.length) { a[0] = last; let i = 0;
      for (;;) { const l = 2 * i + 1, r = l + 1; let m = i;
        if (l < a.length && this.cmp(a[l], a[m]) < 0) m = l;
        if (r < a.length && this.cmp(a[r], a[m]) < 0) m = r;
        if (m === i) break; [a[i], a[m]] = [a[m], a[i]]; i = m; } }
    return top; }
}

function mergeKLists(lists) {
  const h = new MinHeap((a, b) => a.val - b.val);
  for (const node of lists) if (node) h.push(node);
  const dummy = new ListNode(); let tail = dummy;
  while (h.size) {
    const node = h.pop();
    tail.next = node; tail = node;
    if (node.next) h.push(node.next);
  }
  return dummy.next;
}