Remove Duplicates from Sorted List

Walk a sorted linked list once and unlink every node that repeats the value before it.

Given the head of a linked list sorted from smallest to largest, remove the nodes whose value repeats, so that each value appears only once. Return the head of the list, which is still sorted.

Example 1
Input: head = [1, 1, 2]
Output: [1, 2]
Example 2
Input: head = [1, 1, 2, 3, 3]
Output: [1, 2, 3]
Solution

The Idea

A linked list is a chain of small objects called nodes. Each node holds a value and a link to the node after it, in a field named next. The first node is the head, and the last node's next is null. Example 2 is the chain 1 → 1 → 2 → 3 → 3, five nodes, and we want 1 → 2 → 3.

Where can the repeats be? The list is sorted, so equal values always sit side by side. A second 1 can never turn up after the 2. So a node only has to compare its value with the value of the very next node.

And how do we take a node out? In an array, everything after it would have to shift left. In a linked list, it is enough to change one link so that the chain goes around the node. Look at the picture below.

The sorted list 1, 1, 2, 3, 3. In row 1 the current node is the first 1, and the next node holds the same value. In row 2 the copy is unlinked: the current node's next skips it and points to 2, and the current node stays. In row 3 the next value, 2, is different, so the current node moves on to 2.

In row 1, the current node is the first 1, and the next node holds the same value. In row 2, the current node's next skips the copy and points to 2. Walking from the head no longer reaches the copy, so it is unlinked. In row 3, the next value, 2, is different, so the current node moves on to 2.

The same happens further along: from 3, the next node is another 3, which gets unlinked, and then there is no next node left. So the whole job is one walk along the list, where each step either unlinks the next node or moves forward.

Solution Approach

Turning that idea into code means settling three things: how to spot a repeat without keeping a record of the values seen so far, where to stand after unlinking a node, and when the walk stops.

Spotting a repeat

How does a node know its value is a repeat? One simple way is to keep a HashSet of the values seen so far and unlink any node whose value is already in it. That works even on an unsorted list, but it stores every distinct value.

The sorted order makes that memory unnecessary. A repeat always comes straight after the node it repeats, so comparing node.next.val with node.val finds every one. Here node is the current node from the picture.

Staying after an unlink

Why does row 2 keep the current node in place instead of moving on? Because the node that is now next may be one more copy. In 1 → 1 → 1, unlinking the second 1 makes the third 1 the next node, and it must be compared with the first 1 as well.

So the walk moves forward only when the next value is different. By then every copy of the current value has been unlinked, and exactly one node with that value is left.

When the walk stops

The walk needs a next node to compare with, so it goes on while both node and node.next are not null. An empty list and a list of one node never enter the walk and come back as they are. The head is never removed, since the first node of each value is the one that stays.

Java Solution

The method deleteDuplicates works in these steps:

  1. First, start a variable node at head. It is the current node.
  2. Loop while node and node.next are both not null, that is, while there is a next node to compare with.
  3. Inside the loop, if node.next.val equals node.val, unlink the copy with node.next = node.next.next and leave node where it is.
  4. Otherwise, move on with node = node.next.
  5. When the loop ends, return head, which is still the first node of the list.

Around the method sit a small ListNode class, build to make a list from numbers, and show to print a list as [1, 2, 3]. The main method runs both examples, three 1s in a row, a list with two -4s and three 7s, a list with no repeats, a single node and an empty list.

Java
public class RemoveDuplicatesFromSortedList {

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

    public static ListNode deleteDuplicates(ListNode head) {
        ListNode node = head;
        while (node != null && node.next != null) {
            if (node.next.val == node.val) {
                node.next = node.next.next;   // unlink the copy, stay on this node
            } else {
                node = node.next;             // a new value: move on to it
            }
        }
        return head;
    }

    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 n = head; n != null; n = n.next) {
            sb.append(n.val).append(n.next != null ? ", " : "");
        }
        return sb.append("]").toString();
    }

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

Running it prints:

Output
[1, 2]
[1, 2, 3]
[1]
[-4, 0, 7, 9]
[1, 2, 3]
[5]
[]

Look at the third line, [1]. It comes from 1 → 1 → 1: the first node stayed in place while both copies were unlinked, one after the other. In the fourth line, the two -4s became one -4 and the three 7s one 7, while 0 and 9 were left alone.

The fifth line is the list 1 → 2 → 3 coming back unchanged, since no neighbours match. The last two lines never enter the loop: the single node 5 has no next node, and the empty list gives [].

What if the loop also moved on after an unlink, running node = node.next right after node.next = node.next.next? That version prints [1, 1] for the third list and [-4, 0, 7, 7, 9] for the fourth. After skipping one copy it steps onto the next copy, which is then never compared with the value it repeats.

Complexity

The method walks the list once and changes links in place, without making any new nodes.

  • Time: O(n), for a list of n nodes: every pass of the loop either unlinks one node or moves node one step forward, and each of the n nodes can be unlinked or passed only once.
  • Space: O(1). The only extra variable is node. The unlinked nodes are no longer reachable from the head, and Java's garbage collector frees them.

The same problem on an array, where the kept values are moved to the front instead of unlinked, is Remove Duplicates from Sorted Array.