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
Output: [1, 2]
Example 2
Output: [1, 2, 3]
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 nextnextnull
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.
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
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
The sorted order makes that memory unnecessary. A repeat always comes straight after the node it repeats, so comparing node.next.valnode.valnode
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 nodenode.nextnull
Java Solution
The method deleteDuplicates
- First, start a variable
atnode . It is the current node.head - Loop while
andnode are both notnode.next , that is, while there is a next node to compare with.null - Inside the loop, if
equalsnode.next.val , unlink the copy withnode.val and leavenode.next = node.next.next where it is.node - Otherwise, move on with
.node = node.next - When the loop ends, return
, which is still the first node of the list.head
Around the method sit a small ListNodebuildshow[1, 2, 3]main
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:
[1, 2]
[1, 2, 3]
[1]
[-4, 0, 7, 9]
[1, 2, 3]
[5]
[]
Look at the third line, [1]
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.nextnode.next = node.next.next[1, 1][-4, 0, 7, 7, 9]
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
one step forward, and each of the n nodes can be unlinked or passed only once.node - Space: O(1). The only extra variable is
. The unlinked nodes are no longer reachable from the head, and Java's garbage collector frees them.node
The same problem on an array, where the kept values are moved to the front instead of unlinked, is