Remove Duplicates from Sorted List II - Problem

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 sorted as well.

For example, given 1→2→3→3→4→4→5, return 1→2→5.

Unlike the original "Remove Duplicates" problem which keeps one copy of each duplicate, this problem removes all occurrences of duplicated values completely.

Input & Output

Example 1 — Basic Case with Duplicates
$ Input: head = [1,2,3,3,4,4,5]
Output: [1,2,5]
💡 Note: Values 3 and 4 appear twice, so remove all occurrences. Keep only unique values 1, 2, and 5.
Example 2 — Head Node is Duplicate
$ Input: head = [1,1,2,3]
Output: [2,3]
💡 Note: The head node value 1 is duplicated, so both 1's are removed. Only 2 and 3 remain.
Example 3 — All Elements are Duplicates
$ Input: head = [1,1,2,2]
Output: []
💡 Note: Every value appears exactly twice, so all nodes are removed, resulting in an empty list.

Constraints

  • The number of nodes in the list is in the range [0, 300]
  • -100 ≤ Node.val ≤ 100
  • The list is guaranteed to be sorted in ascending order

Visualization

Tap to expand
Remove Duplicates from Sorted List II INPUT Sorted Linked List: 1 2 3 3 4 4 5 NULL Unique Duplicate Input Array: [1, 2, 3, 3, 4, 4, 5] Remove ALL occurrences of duplicated values ALGORITHM STEPS 1 Create Dummy Node Add sentinel before head D 1 2 Two Pointer Scan prev stays at last unique prev D curr 3 3 3 Detect Duplicates Compare curr with next if curr.val == curr.next.val skip ALL with same val 4 Reconnect List prev.next = curr.next prev.next skips dups Return dummy.next FINAL RESULT Cleaned Linked List: 1 2 5 --> NULL Removed Nodes: 3 3 4 4 Output Array: [1, 2, 5] OK - All dups removed! Time: O(n) | Space: O(1) Key Insight: Use a dummy node to handle edge cases where the head itself might be a duplicate. The prev pointer stays at the last confirmed unique node, while we scan ahead to detect and skip all nodes with duplicate values. This differs from keeping one copy - we remove ALL occurrences. TutorialsPoint - Remove Duplicates from Sorted List II | Optimal Solution
Asked in
Microsoft 45 Amazon 38 Google 32 Facebook 28
187.5K Views
Medium-High Frequency
~25 min Avg. Time
3.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen