Merge K sorted linked lists.
Problem
Merge k sorted lists into one sorted list. With N total nodes, aim for better than O(N × k).
Approach
Put the head of each list into a min-heap ordered by value. Repeatedly poll the smallest node, append it to the result, and push its successor. The heap never holds more than k nodes. (Divide and conquer, merging lists pairwise, has the same O(N log k) complexity.) This is the same k-way merge used to merge sorted files in external sorting and LSM-tree compaction.
import java.util.Comparator;
import java.util.PriorityQueue;
class MergeKSortedLists {
static final class Node {
int val;
Node next;
Node(int val, Node next) { this.val = val; this.next = next; }
}
static Node merge(Node[] lists) {
PriorityQueue<Node> heap = new PriorityQueue<>(Comparator.comparingInt(n -> n.val));
for (Node head : lists) if (head != null) heap.offer(head);
Node dummy = new Node(0, null), tail = dummy;
while (!heap.isEmpty()) {
Node smallest = heap.poll();
tail.next = smallest;
tail = smallest;
if (smallest.next != null) heap.offer(smallest.next);
}
return dummy.next;
}
static Node list(int... values) {
Node head = null;
for (int i = values.length - 1; i >= 0; i--) head = new Node(values[i], head);
return head;
}
public static void main(String[] args) {
Node merged = merge(new Node[] {list(1, 4, 5), list(1, 3, 4), list(2, 6)});
StringBuilder sb = new StringBuilder();
for (Node n = merged; n != null; n = n.next) sb.append(n.val).append(' ');
System.out.println(sb.toString().trim()); // 1 1 2 3 4 4 5 6
}
}Complexity
O(N log k) time; O(k) heap space.
Follow-up questions interviewers ask
Try answering each one before you open it.
How would you merge 100 sorted files of 10 GB each with 2 GB of RAM?
External k-way merge: open a buffered reader on each file, keep one current record per file in a min-heap of 100 entries, and stream the output to disk in a buffered writer. Memory use is the heap plus I/O buffers (for example 100 × 8 MB), independent of file size. If the files were unsorted, first sort chunks that fit in memory and write them as sorted runs, then merge.