Merge Two Sorted Linked Lists And Remove Duplicates

Merge two sorted linked lists into one sorted list in which each value appears once.

Given the heads of two linked lists, list1 and list2, each sorted in increasing order, merge them into one sorted list in which every value appears only once. Build the result from the nodes of the two lists, not from new nodes, and return its head.

Example 1
Input: list1 = [1, 2, 4], list2 = [1, 3, 4]
Output: [1, 2, 3, 4]
Example 2
Input: list1 = [1, 1, 2], list2 = [2, 2]
Output: [1, 2]
Explanation: repeats can come from within one list as well as from both lists.
Example 3
Input: list1 = [], list2 = [0]
Output: [0]
Solution

The Idea

Picture two stacks of numbered cards, each sorted with the smallest on top, and you want one sorted pile with every number only once. You would look at the top card of both stacks, take the smaller one, and repeat until both stacks are empty.

Here the stacks are linked lists. A linked list is a chain of nodes: each node holds a value and a pointer, called next, to the node after it. The first node is the head, and the last node's next is null.

Take Example 2: list1 is 1, 1, 2 and list2 is 2, 2. Merging them the usual way, by taking the smaller front node each time, gives the nodes in the order 1, 1, 2, 2, 2. That order is sorted, but the answer is just 1, 2. Some repeats sit inside one list, like the two 1s in list1, and some come from both lists, like the 2s.

So how do we spot a repeat while merging? Checking each new node against every node kept so far would work, but that is a search for every node. Look at the picture below.

list1 is 1, 1, 2 and list2 is 2, 2. The merge takes the nodes in the order 1, 1, 2, 2, 2. Each node is compared with the last kept value: the first 1 and the first 2 are kept, the other three are skipped, and the result is 1, 2.

The row labelled node shows the five nodes in the order the merge takes them. Under each one, the row labelled last kept value shows the value of the node most recently put into the result. The second 1 meets a last kept value of 1, so it is skipped. The first 2 meets 1, so it is kept, and the two 2s from list2 both meet 2 and are skipped. The row labelled result reads 1, 2.

Because the merge hands out nodes in sorted order, all copies of a value arrive one right after another. So a node is a repeat exactly when its value equals the last kept value, and one comparison per node is enough.

Solution Approach

One simple way merges first and removes the repeats afterwards; doing both in a single pass means settling three things: how to take the nodes in sorted order, how to compare each node with the last kept one, and how to end the result list.

Merging first, then removing repeats

Can known pieces do the job? Merge the lists as in Merge Two Sorted Lists, then walk the merged list again and unlink every node equal to the one before it, as in Remove Duplicates from Sorted List. That is correct, but it walks every node twice. The merge already meets the nodes in sorted order, so it can drop the repeats as it goes.

Taking the nodes in sorted order

Which node comes next? The smaller of the two front nodes. The variables list1 and list2 start at the two heads and act as markers: taking a node moves that list's marker on to its next. When one list runs out, the other list's front node is taken. On a tie, the code takes from list1; either choice works, because the second copy is skipped anyway.

A plain merge attaches whatever is left of the longer list in one step. Here the loop keeps going until both lists are empty, because the leftover nodes can be repeats too. With list1 = [3, 3] and list2 = [3], the 3 from list2 is left over once list1 runs out, and it equals the last kept value.

Comparing with the last kept node

Where does the last kept value come from? The result grows by attaching nodes at its end, so the code keeps a pointer, tail, to the last node attached. A new node is kept when its value differs from tail.val.

The very first node has nothing to compare with. An extra node placed before the result's first real node, called a dummy node, handles that: tail starts on it, and while tail is still the dummy, the next node is kept whatever its value. At the end, the result starts at dummy.next.

Ending the result list

What happens to the skipped nodes? They are never attached, but every kept node still has its old next pointer. For each kept node except the last, the next node kept overwrites that pointer. The last kept node's next is never overwritten, so it may still lead to a skipped node.

Take list1 = [2, 3, 3] and list2 = [1]. The first 3 of list1 is the last node kept, and its next still points at the second 3. Setting tail.next = null after the loop ends the result there.

Java Solution

The method mergeWithoutDuplicates works in these steps:

  1. First, create the dummy node dummy and point tail at it. tail always marks the last node of the result.
  2. Loop while list1 or list2 still has nodes. Inside, put the smaller front node into smaller: the one from list1 when list2 is empty or list1's front value is smaller or equal, otherwise the one from list2. Move that list's marker to its next node.
  3. If tail is still dummy, or tail.val differs from smaller.val, attach the node with tail.next = smaller and move tail to it. Otherwise leave smaller out.
  4. After the loop, set tail.next = null so the result does not run on into a skipped node, and return dummy.next.

The class also has a small ListNode class and two helpers: build makes a list from numbers, and show prints a list as [1, 2]. The main method runs the three examples, then [3, 3] with [3], [2, 3, 3] with [1], and two empty lists.

Java
public class MergeTwoSortedListsAndRemoveDuplicates {

    static class ListNode {
        int val;
        ListNode next;
        ListNode(int val) { this.val = val; }
    }

    public static ListNode mergeWithoutDuplicates(ListNode list1, ListNode list2) {
        ListNode dummy = new ListNode(0);
        ListNode tail = dummy;
        while (list1 != null || list2 != null) {
            ListNode smaller;
            if (list2 == null || (list1 != null && list1.val <= list2.val)) {
                smaller = list1;
                list1 = list1.next;
            } else {
                smaller = list2;
                list2 = list2.next;
            }
            if (tail == dummy || tail.val != smaller.val) {  // a new value: keep it
                tail.next = smaller;
                tail = smaller;
            }
        }
        tail.next = null;   // the last kept node may still point at a skipped node
        return dummy.next;
    }

    static ListNode build(int... values) {
        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 head) {
        StringBuilder sb = new StringBuilder("[");
        for (ListNode node = head; node != null; node = node.next) {
            sb.append(node.val).append(node.next != null ? ", " : "");
        }
        return sb.append("]").toString();
    }

    public static void main(String[] args) {
        System.out.println(show(mergeWithoutDuplicates(build(1, 2, 4), build(1, 3, 4))));
        System.out.println(show(mergeWithoutDuplicates(build(1, 1, 2), build(2, 2))));
        System.out.println(show(mergeWithoutDuplicates(build(), build(0))));
        System.out.println(show(mergeWithoutDuplicates(build(3, 3), build(3))));
        System.out.println(show(mergeWithoutDuplicates(build(2, 3, 3), build(1))));
        System.out.println(show(mergeWithoutDuplicates(build(), build())));
    }
}

Running it prints:

Output
[1, 2, 3, 4]
[1, 2]
[0]
[3]
[1, 2, 3]
[]

The second line, [1, 2], is Example 2, the walk shown in the picture. The fourth line is a single [3]: the 3 from list2 came after list1 ran out, and the loop still compared it with the last kept 3 and skipped it.

The fifth line, [1, 2, 3], stops at the first 3 because of tail.next = null. With that line removed, the same input printed [1, 2, 3, 3], and [3, 3] with [3] printed [3, 3]: in both, the last kept node still led to the skipped 3. The last line, [], comes from two empty lists: the loop never runs, and dummy.next is null.

The original implementation and its tests are on GitHub: MergeTwoSortedListsRemoveDuplicates.java and TestMergeTwoSortedListsRemoveDuplicates.java.

Complexity

Each pass of the loop takes exactly one node from one of the two lists, whether that node is kept or skipped.

  • Time: O(m + n), for lists of m and n nodes: the loop runs once per node of either list, and each pass does one comparison of front values and one comparison with the last kept value.
  • Space: O(1). The only new node is dummy. Kept nodes are relinked by changing their next pointers, and skipped nodes are simply never attached.