Start learning free

LESSON 427 OF 671 · LINKED LISTS

Remove Duplicates from Sorted Linked List

Practice O(n)

You get the head of a sorted linked list. Equal values sit next to each other.

Remove every node whose value appears more than once. Return the head of the list that is left.

The values that appear only once stay, in the same order.

 

Example 1:

Input: head = [2,2,3,5,5,5,8]
Output: [3,8]
Explanation: 2 appears twice and 5 appears three times.
All five of those nodes go.
3 and 8 appear once, so 3 -> 8 is left.

Example 2:

Input: head = [6,6,9,9]
Output: []
Explanation: Every value repeats.
No node is left, so return null.

Example 3:

Input: head = [-3,4,10]
Output: [-3,4,10]
Explanation: No value repeats.
The list stays as it is.

 

Constraints:

  • 0 to 300 nodes (the list can be empty).
  • Each value is from -100 to 100.
  • The values are in ascending order.
  • A value can repeat.
STEP 1 OF 13
    Ctrl + Enter to check