Remove Duplicates from Sorted List (LeetCode 83): Solution and Explanation

Easy
Linked List

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

  1. Set curr = head.
  2. While curr and curr.next both exist, compare curr.next.val with curr.val.
  3. If they are equal, unlink the neighbour with curr.next = curr.next.next and keep curr in place, because the new neighbour may be another copy.
  4. If they differ, the value at curr is settled, so move curr = curr.next.
  5. When the loop ends, every run has been collapsed to its first node. Return head.

Step-by-step example

head = [1,1,2]
  1. curr starts on the first node, value 1. Its neighbour also holds 1.
  2. 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.
  3. curr stays on the first 1 and compares again. The neighbour is now 2, which is different, so curr moves to 2.
  4. curr.next is null, so the loop stops. Returning head gives [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 head
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

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.

Space

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 curr right 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 curr in the loop condition and then reading curr.next.val when curr.next is null. Both curr and curr.next must exist.
  • Returning curr instead of head. By the end, curr sits 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.