Remove Duplicates from Sorted List II Medium 0 attempts
LeetCode ↗

Remove Duplicates from Sorted List II

Medium Linked List LeetCode

You're given the head of a singly linked list sorted in non-decreasing order. Any node whose value occurs more than once anywhere in the list must be removed entirely — not trimmed down to a single copy — so that only values appearing exactly once are left behind. Return the head of the resulting 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,2,3,3,4,4,5]
Output
[1,2,5]

Example 2

Input
head = [1,1,1]
Output
[]
Constraints
  • 0 to 300 nodes
  • -100 <= Node.val <= 100
  • List is sorted
Test Cases (2)
Case 1
Args: [[1,2,3,3,4,4,5]] Expected: [1,2,5]
Case 2
Args: [[1,1,1]] Expected: []
Topics

Dummy Head + Skip Groups

javascript
function deleteDuplicates(head) {
  const dummy = {next: head};
  let prev = dummy;
  while (prev.next) {
    let curr = prev.next;
    while (curr.next && curr.val === curr.next.val) curr = curr.next;
    if (prev.next === curr) prev = prev.next;
    else prev.next = curr.next;
  }
  return dummy.next;
}

Time: O(n) | Space: O(1)

Saved in this browser only. Private to you.

JavaScript