Heap approach

Node mergeK(List> lists) {
  PriorityQueue> pq = new PriorityQueue<>((a, b) -> a.val - b.val);
  for (Node l : lists) if (l != null) pq.offer(l);
  Node dummy = new Node<>(0);
  Node tail = dummy;
  while (!pq.isEmpty()) {
    Node min = pq.poll();
    tail.next = min;
    tail = tail.next;
    if (min.next != null) pq.offer(min.next);
  }
  return dummy.next;
}
Advertisement

Complexity

O(N log K) time where N = total nodes across all lists. O(K) heap space.

Advertisement

Divide + conquer alternative

Repeatedly merge pairs. Same O(N log K) bound. Slightly less overhead than heap for cache reasons.

Applications

External sort final merge. LSM compactions. Multi-shard result merging in databases.