Skip to problem
←

Remove Duplicates from Sorted List II

Medium 0 attempts

Given a singly linked list sorted in nondecreasing order, remove every occurrence of any value that appears more than once. Return the head of the list containing only values that appeared exactly once in the original list.

Reuse the surviving original nodes, preserve their order, and do not change their values. The returned head may differ from the input head. Return null when the input is empty or no nodes survive.

For [1, 2, 3, 3, 4, 4, 5], return [1, 2, 5]. Both 3s and both 4s are removed; do not retain one representative from those groups.

Examples display lists as arrays; your function receives nodes with val and next properties.

Function contract

Implement deleteDuplicates(head). Linked lists use value arrays. The editor passes nodes with val and next properties; [] becomes null.

Output: Return the head linking only original nodes whose values occur exactly once, in original order; return null if none remain.

Example 1

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
  • The list is sorted in nondecreasing order.
Topics

Dummy Head and Equal-Value Runs

Place a dummy node before the head so a repeated group at the beginning can be removed just like any other group. Keep prev at the last retained node, initially the dummy.

Starting from prev.next, advance curr to the end of the equal-value run. If curr is still the run's first node, the value occurred once, so retain it and advance prev. Otherwise bypass the entire run by assigning prev.next = curr.next, leaving prev in place.

Sorted order guarantees all occurrences of a value form one run. Every node is examined a constant number of times, and surviving node identities and values are unchanged. The dummy is only a helper and is not returned as part of the list.

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)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript