Remove Duplicates from Sorted List
You get the head of a singly linked list whose values are sorted in non-decreasing order. Remove duplicates so each value appears at most once. Keep the list sorted. Return the head of the modified list.
Do not allocate a whole new list for the result; reuse nodes and adjust pointers.
Example 1
- Input:
head = [1, 1, 2] - Output:
[1, 2]
Example 2
- Input:
head = [1, 1, 2, 3, 3] - Output:
[1, 2, 3]
Constraints
- The list has between
0and300nodes -100 <= Node.val <= 100- The list is sorted in non-decreasing order
Sample Input
—
Sample Output
—
Constraints
- 0 to 300 nodes
- -100 <= Node.val <= 100
- List is sorted in ascending order
Topics
One Pass
function deleteDuplicates(head) {
let curr = head;
while (curr && curr.next) {
if (curr.val === curr.next.val) curr.next = curr.next.next;
else curr = curr.next;
}
return head;
}
Time: O(n) | Space: O(1)
Saved in this browser only. Private to you.