82. Remove Duplicates from Sorted List II โ๐ข
Last updated
Last updated
Difficulty: Medium
- Tags: Linked List
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.
๐น Example 1:
Input:
Output:
๐น Example 2:
Input:
Output:
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.
To solve this problem, we need to identify and remove all nodes with duplicate values. Using a dummy node simplifies edge cases, especially when duplicates appear at the start of the list.
Dummy Node:
A dummy node is added at the beginning of the list to handle edge cases where the first few nodes are duplicates.
Traversing the List:
If a node and its next
node have the same value, skip all nodes with that value.
Handling Duplicates:
Once duplicates are skipped, the prev
pointer connects to the first non-duplicate node.
Returning the Result:
The new list starts from dummy.next
.
O(n): The entire list is traversed once.
O(1): The solution uses constant extra space.
This approach works efficiently without requiring additional data structures, maintaining the sorted property of the linked list.
You can find the full solution here.