Remove Duplicates from Sorted List - Problem

Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.

The linked list is sorted in ascending order.

Input & Output

Example 1 — Basic Duplicates
$ Input: head = [1,1,2]
Output: [1,2]
💡 Note: The linked list has duplicate 1s. After removing duplicates, we get [1,2] with each element appearing only once.
Example 2 — Multiple Groups
$ Input: head = [1,1,2,3,3]
Output: [1,2,3]
💡 Note: We have two groups of duplicates: two 1s and two 3s. Remove one from each group to get [1,2,3].
Example 3 — No Duplicates
$ Input: head = [1,2,3]
Output: [1,2,3]
💡 Note: The list has no duplicates, so it remains unchanged.

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 INPUT Sorted Linked List 1 1 2 NULL Duplicates detected Input Values: head = [1, 1, 2] Sorted ascending order Properties: - List is sorted - Contains duplicates - 3 nodes total ALGORITHM STEPS Single Pass Traversal 1 Initialize Pointer Set current = head 2 Compare Adjacent Check curr.val == curr.next.val 3 Skip Duplicate curr.next = curr.next.next 4 Move Forward Else curr = curr.next Traversal Process: 1 1 2 Skip! Red node removed, link bypassed Time: O(n) | Space: O(1) FINAL RESULT Cleaned Linked List 1 2 NULL OK - No Duplicates Output: [1, 2] Before vs After [1, 1, 2] --> [1, 2] 1 duplicate removed Key Insight: Since the list is SORTED, all duplicates are adjacent. We only need to compare each node with its next neighbor. When a duplicate is found, we skip it by changing the pointer (curr.next = curr.next.next) without extra space. This achieves O(n) time complexity with O(1) space - optimal single pass solution! TutorialsPoint - Remove Duplicates from Sorted List | Single Pass Traversal Approach
Asked in
Facebook 32 Amazon 28 Microsoft 24 Google 19
125.0K Views
High Frequency
~15 min Avg. Time
3.6K 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