Merge K Sorted Lists

Merge several sorted linked lists into one sorted list by always taking the smallest front node.

Given an array lists of k linked lists, each sorted from smallest to largest value, join all their nodes into one linked list that is also sorted, and return it. Any of the lists may be empty, and so may the array itself.

Example 1
Input: lists = [[1, 4, 5], [1, 3, 4], [2, 6]]
Output: [1, 1, 2, 3, 4, 4, 5, 6]
Example 2
Input: lists = []
Output: []
Example 3
Input: lists = [[]]
Output: []
Solution

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.

Lists A (1, 4, 5), B (1, 3, 4) and C (2, 6). The min-heap of fronts holds 1 from A, 1 from B and 2 from C. The smallest, 1 from A, comes out into the merged list, and then A's next node, 4, joins the heap.

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 PriorityQueue, from java.util, is one: poll() removes and returns its smallest item, and add() puts a new one in. It needs to know what "smallest" means for a node, so we hand it a comparator, a small function that compares two items:

(a, b) -> Integer.compare(a.val, b.val)

In the code, each node is a ListNode object with two fields: val, the value it holds, and next, the link to the node after it. The comparator compares two nodes by val. Because the smaller value counts as smaller, the queue stays a min-heap. Swapping a and b would turn it into a max-heap, which hands out the largest first.

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 null, and PriorityQueue does not accept null. So an empty list is simply left out of the heap. If every list is empty, or there are none, the heap starts empty and the answer is an empty list.

Java Solution

The method mergeKLists works in these steps:

  1. First, create the min-heap heap, a PriorityQueue<ListNode> built with the comparator that compares val.
  2. Loop over lists and add the front node, head, of every list that is not empty.
  3. Create the placeholder node dummy, and a variable tail that points at the last node of the merged list, which is dummy for now.
  4. While the heap is not empty, take out its smallest node, smallest, link it after tail, and move tail to it. If smallest.next is not null, that next node of the same list joins the heap.
  5. When the heap is empty, return dummy.next, the first real node of the merged list.

The class also has a small ListNode class, build to make a linked list from values, and show to print one as [1, 4, 5]. The main method runs the three examples, then lists with negative and repeated values around an empty list, and a single list on its own.

Java
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:

Output
[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], as in Example 1. The next two lines, both [], come from no lists at all and from one empty list: in both cases the heap never gets a node, and dummy.next is still null.

Look at the fourth line, [-3, -3, 0, 0, 7]. Its input was [-3, 0, 0], an empty list, and [-3, 7]. The empty list was left out, and the two -3s, one from each list, both came out before the 0s. The last line shows that a single list, [2, 9], comes back unchanged.

The head != null check matters for the third and fourth lines, whose inputs contain an empty list. Without it, the first loop would call heap.add(null) for the empty list, and PriorityQueue answers that with a NullPointerException before any merging starts.

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 Merge Two Sorted Lists.