Remove Duplicates from Sorted List
You're given the head of a singly linked list whose values are already arranged in non-decreasing order. Delete duplicate values so each distinct value remains only once, keeping the list sorted, and return the head of the updated list.
Solve it in place — reuse the existing nodes and simply adjust their pointers rather than building a new list.
Input Format
Implement deleteDuplicates(head). Inputs below show JavaScript function arguments; there is no stdin parsing.
Linked lists use value arrays. The editor passes nodes with val and next properties; [] becomes null.
Output Format
Return the result described in the statement.
Returned list heads are displayed as value arrays; a null head is [].
Sample Input and Output
Example 1 · Run Sample
Input
head = [1,1,2,3,3] Output
[1,2,3] Example 2
Input
head = [] Output
[] Constraints
- 0 to 300 nodes
- -100 <= Node.val <= 100
- List is sorted in ascending order
Test Cases (2)
Case 1
Args: [[1,1,2,3,3]]
Expected: [1,2,3]
Case 2
Args: [[]]
Expected: []
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.