AlgoInsight

DSA problem

Remove Duplicates from Sorted List II

MediumLinked ListPattern: Linked Listtop300AmazonMicrosoftBloombergAdobeGoogle

Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list still sorted.

This is the stricter sibling of the basic duplicate-removal problem. There you keep one copy of every value; here you must remove a value entirely if it appears more than once. A run of three nodes with value 2 disappears completely rather than collapsing to a single node.

The complication is that the head itself may be a duplicate that must be deleted. To handle that uniformly, prepend a dummy node before the head and track a prev pointer that always references the last confirmed-distinct node, initially the dummy.

The optimal approach makes a single pass. A current pointer scans forward; whenever current.val equals current.next.val, advance current past the entire run of equal values, then link prev.next directly to the node after that run, skipping every duplicate. If current has no equal neighbor, it is unique, so move prev forward to it. Returning dummy.next yields a list of values that each appeared exactly once, all in O(n) time and O(1) space.

Examples

Example 1
Input: head = [1,2,3,3,4,4,5]
Output: [1,2,5]
Explanation: Values 3 and 4 each appear twice, so both are removed entirely, leaving the distinct values 1, 2, and 5.
Example 2
Input: head = [1,1,1,2,3]
Output: [2,3]
Explanation: The value 1 appears three times and is removed completely; 2 and 3 are unique and remain.
Example 3
Input: head = [1,1]
Output: []
Explanation: The only value appears twice, so the entire list is removed and the result is empty.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

linked-listtwo-pointersin-place

Browse all DSA problems