Remove all duplicates from a sorted list
Challenge · Write code · about 18 min
Given the head of a sorted singly linked list, delete every node whose value appears more than once, so only values that were unique remain. Keep the remaining nodes in order and return the head.
This removes all copies, not just the extra ones: [1, 1, 2] becomes [2].
Example 1
Input:
[[1,2,3,3,4,4,5]]
Output:
[1,2,5]
Example 2
Input:
[[1,1,1,2,3]]
Output:
[2,3]
The head is part of a run, so the head changes.
Constraints
- 0 ≤ number of nodes ≤ 5,000
- -1,000 ≤ node value ≤ 1,000
- The list is sorted in non-decreasing order.
Learn the idea first: Singly linked lists: traverse, insert, delete, a visual lesson.
More Singly linked lists: traverse, insert, delete problems
- Insert after a node Warm-up
- Length of a linked list Warm-up
- Delete by value Standard
- Remove the nth node from the end Standard
- Spot the bug: arrows set in the wrong order Standard