Merge K Sorted Lists
Merge several sorted linked lists into one sorted list by always taking the smallest front node.
Given an array lists
Example 1
Output: [1, 1, 2, 3, 4, 4, 5, 6]
Example 2
Output: []
Example 3
Output: []
The Idea
Think of three queues of people, each already lined up by ticket number, that must become one line, still in ticket order. You would not shuffle everyone. You would look at the person at the front of each queue and wave the lowest number through, again and again.
Example 1 is the same job with numbers. Call its three lists A, B and C. List A is a chain of three nodes: the node holding 1 links to the node holding 4, and that one links to 5. List B is 1, 3, 4, and list C is 2, 6. Since each list is sorted, its front node holds its smallest value.
So the smallest value of all must be at the front of some list. Here the fronts are 1, 1 and 2, and a 1 goes first. Once that node leaves list A, the node holding 4 becomes A's new front, and the question repeats with fronts 4, 1 and 2. How do we find the smallest front quickly, again and again, while the fronts keep changing?
A container that always hands out its smallest item first, and lets new items join at any time, is called a min-heap. Keep the fronts in one. Look at the picture below.
The box labelled "min-heap of fronts" holds one node from each list: 1 from A, 1 from B and 2 from C. The smallest, 1 (A), comes out and goes to the end of the merged list. Then, following the dashed arrow, A's next node, 4, joins the heap in its place.
That one move, repeated, does the whole merge. The heap gives out 1 (B) next, then 2 (C), then 3, and so on, until every node has passed through it into the merged list: 1, 1, 2, 3, 4, 4, 5, 6.
Solution Approach
Turning that idea into code means settling four things: why a heap beats looking at every front, which Java class holds the fronts and how it compares nodes, how to build the merged list, and what to do with empty lists.
Finding the smallest front
Why not simply compare all k fronts each time? That works, but each node then costs k comparisons. With 1,000 lists and a million nodes in total, that is about a billion comparisons.
A heap of k items keeps them partly ordered, so taking out the smallest or adding a new one takes about log2 k steps. For 1,000 lists that is about 10 steps per node instead of 1,000.
The heap in Java
Which class gives us a min-heap? Java's PriorityQueuejava.utilpoll()add()
(a, b) -> Integer.compare(a.val, b.val)
In the code, each node is a ListNodevalnextvalab
Building the merged list
Where does each node go once it leaves the heap? It goes to the end of the merged list, so we keep a variable that points at the last node there. The nodes are relinked, not copied: the merged list is made of the same nodes as the input lists.
Before the first node arrives, the merged list has no last node. A placeholder node at the start, often called a dummy head, removes that special case. The first real node is linked after the placeholder, like every other node, and the answer starts right after it.
Empty lists
What does an empty list give us? Its front is nullPriorityQueuenull
Java Solution
The method mergeKLists
- First, create the min-heap
, aheap built with the comparator that comparesPriorityQueue<ListNode> .val - Loop over
and add the front node,lists , of every list that is not empty.head - Create the placeholder node
, and a variabledummy that points at the last node of the merged list, which istail for now.dummy - While the heap is not empty, take out its smallest node,
, link it aftersmallest , and movetail to it. Iftail is notsmallest.next , that next node of the same list joins the heap.null - When the heap is empty, return
, the first real node of the merged list.dummy.next
The class also has a small ListNodebuildshow[1, 4, 5]main
import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;
public class MergeKSortedLists {
static class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; }
}
public static ListNode mergeKLists(ListNode[] lists) {
PriorityQueue<ListNode> heap =
new PriorityQueue<>((a, b) -> Integer.compare(a.val, b.val)); // min-heap
for (ListNode head : lists) {
if (head != null) {
heap.add(head); // the front node of every non-empty list
}
}
ListNode dummy = new ListNode(0);
ListNode tail = dummy;
while (!heap.isEmpty()) {
ListNode smallest = heap.poll(); // the smallest front of all
tail.next = smallest;
tail = smallest;
if (smallest.next != null) {
heap.add(smallest.next); // the next node of that list moves up
}
}
return dummy.next;
}
static ListNode build(int... values) { // [1, 4, 5] becomes 1 -> 4 -> 5
ListNode dummy = new ListNode(0);
ListNode tail = dummy;
for (int v : values) {
tail.next = new ListNode(v);
tail = tail.next;
}
return dummy.next;
}
static String show(ListNode node) { // 1 -> 4 -> 5 prints as [1, 4, 5]
List<Integer> values = new ArrayList<>();
for (; node != null; node = node.next) {
values.add(node.val);
}
return values.toString();
}
public static void main(String[] args) {
System.out.println(show(mergeKLists(new ListNode[] {
build(1, 4, 5), build(1, 3, 4), build(2, 6)})));
System.out.println(show(mergeKLists(new ListNode[] {})));
System.out.println(show(mergeKLists(new ListNode[] {build()})));
System.out.println(show(mergeKLists(new ListNode[] {
build(-3, 0, 0), build(), build(-3, 7)})));
System.out.println(show(mergeKLists(new ListNode[] {build(2, 9)})));
}
}
Running it prints:
[1, 1, 2, 3, 4, 4, 5, 6]
[]
[]
[-3, -3, 0, 0, 7]
[2, 9]
The merge of lists A, B and C gives [1, 1, 2, 3, 4, 4, 5, 6][]dummy.nextnull
Look at the fourth line, [-3, -3, 0, 0, 7][-3, 0, 0][-3, 7][2, 9]
The head != nullheap.add(null)PriorityQueueNullPointerException
Complexity
Every node passes through the heap once, and the heap never holds more than one node from each list.
- Time: O(N log k), because each of the N nodes in all the lists is added to the heap once and polled once, and each such step costs about log2 k on a heap of at most k nodes. The first loop also looks at each of the k list heads once.
- Space: O(k), because the heap holds at most one front node per list, and the merged list reuses the input nodes, so the only new node is
.dummy
The same merge for just two lists, where a simple comparison replaces the heap, is