Remove Duplicates from Sorted List (LeetCode 83): Solution and Explanation
You get the head of a singly linked list sorted in non-decreasing order. Remove the extra copies so that each value appears once, keep the list sorted, and return its head.
Intuition
Sorting does most of the work for you. In a sorted list, every copy of a value sits in one consecutive run, so a node is a duplicate exactly when it has the same value as the node right before it. You never need a set or a second pass to remember what you have seen.
That suggests a single pointer curr that looks one step ahead. If curr.next has the same value, it is an extra copy, and you can drop it from the list by pointing curr.next one node further. The dropped node is simply no longer reachable from the head.
The subtle part is when to move. After unlinking a duplicate, the new curr.next might be yet another copy of the same value, so curr must stay where it is and compare again. Only when the neighbour holds a different value is curr finished, and then it steps forward.
The head itself is never removed, because the first node of every run is always the one that survives. That means you can return the original head without a dummy node.
Approach: Single pointer, unlink equal neighbours
- Set
curr = head. - While
currandcurr.nextboth exist, comparecurr.next.valwithcurr.val. - If they are equal, unlink the neighbour with
curr.next = curr.next.nextand keepcurrin place, because the new neighbour may be another copy. - If they differ, the value at
curris settled, so movecurr = curr.next. - When the loop ends, every run has been collapsed to its first node. Return
head.
Step-by-step example
head = [1,1,2]
currstarts on the first node, value 1. Its neighbour also holds 1.- The values are equal, so set
curr.next = curr.next.next. The first 1 now points straight at 2 and the second 1 is out of the list. currstays on the first 1 and compares again. The neighbour is now 2, which is different, socurrmoves to 2.curr.nextis null, so the loop stops. Returningheadgives [1,2].
Code: Python, Java, C++
1class Solution:
2 def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
3 curr = head
4 while curr and curr.next:
5 if curr.next.val == curr.val:
6 curr.next = curr.next.next
7 else:
8 curr = curr.next
9 return head1class Solution {
2 public ListNode deleteDuplicates(ListNode head) {
3 ListNode curr = head;
4 while (curr != null && curr.next != null) {
5 if (curr.next.val == curr.val) {
6 curr.next = curr.next.next;
7 } else {
8 curr = curr.next;
9 }
10 }
11 return head;
12 }
13}1class Solution {
2public:
3 ListNode* deleteDuplicates(ListNode* head) {
4 ListNode* curr = head;
5 while (curr && curr->next) {
6 if (curr->next->val == curr->val) {
7 curr->next = curr->next->next;
8 } else {
9 curr = curr->next;
10 }
11 }
12 return head;
13 }
14};Time and space complexity
O(n)
Every loop iteration either unlinks one node or moves curr forward one node, and each node can be unlinked or passed at most once, so there are fewer than n iterations.
O(1)
The list is changed in place using one extra pointer, no matter how long it is.
Other approaches
Run skipping with an inner loop (time O(n), space O(1))
For each curr, advance a second pointer past the whole run of equal values and then link curr to the first different node in one assignment. It does the same work, just grouped per run, and some people find it easier to read.
Recursion (time O(n), space O(n))
Deduplicate head.next recursively, then return head.next if it has the same value as head, otherwise attach it and return head. Short, but it uses a call stack as deep as the list.
Rebuild from a set (time O(n), space O(n))
Collect the values, drop duplicates, and build a new list. It ignores the sorted order, allocates new nodes, and is only worth it if the list were unsorted.
Common mistakes
- Advancing
currright after unlinking a duplicate. With three or more equal values in a row, that skips a comparison and leaves a copy behind, for example [1,1,1] would become [1,1]. - Checking only
currin the loop condition and then readingcurr.next.valwhencurr.nextis null. Bothcurrandcurr.nextmust exist. - Returning
currinstead ofhead. By the end,currsits on the last node, not the start of the list. - Reaching for a hash set. It works but wastes memory, since sorting already guarantees that copies are adjacent.
Frequently asked questions
Why does curr not move after removing a duplicate?
The node that becomes the new curr.next has not been compared yet and may hold the same value. Staying put lets the loop check it on the next iteration, which is how a run of any length collapses to one node.
Do I need a dummy node for this problem?
No. The first node of each run is always kept, and the head is the first node of the first run, so it can never be deleted. A dummy node is needed in the follow-up problem where every copy of a duplicated value is removed.
What happens to the removed nodes?
Nothing points to them anymore, so they are unreachable from the head. In garbage-collected languages they are reclaimed automatically; in C++ you could delete them, but the judge does not require it.
What is the time and space complexity?
O(n) time, because each iteration either removes a node or moves past one, and O(1) extra space, because only one pointer is used.