Skip to problem
←

Remove Duplicates from Sorted List

Easy 0 attempts

Given the head of a singly linked list sorted in nondecreasing order, remove repeated occurrences so that one node for each distinct value remains. Return the head of the resulting sorted list, or null for an empty input.

Reuse existing nodes and only adjust links; do not create replacement nodes or change their values. Any original node from a run of equal values may be retained. This problem keeps one occurrence of a repeated value rather than deleting the entire run.

For [1, 1, 2, 3, 3], return a list with values [1, 2, 3]. For [2, 2, 2], return a single original node with value 2.

Examples display value arrays, but 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 of a sorted list containing one original node per distinct value, or null for an empty input. The runner displays node values as an array.

Example 1

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

Skip Adjacent Duplicates

Sorted order makes equal values adjacent. Keep curr at the last retained node. When its next node has the same value, bypass that next node by assigning curr.next = curr.next.next.

Do not advance curr after a removal: another duplicate may now be immediately next. Advance only when the next value differs. This retains the first node of each run, preserves its value, and removes every other occurrence in one pass.

An empty or single-node list needs no changes. Return the original head, which is retained by this implementation.

javascript
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)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript