MediumLinked ListTwo PointersRecursion

Remove Duplicates from Sorted List II

LeetCode
1 approach, code in all languages

You are given the head of a sorted singly linked list. Remove every node whose value appears more than once, keeping only the values that are unique across the entire list.

Unlike the simpler variant that keeps one copy of each value, here a value that repeats is deleted completely. The remaining nodes must stay in their original sorted order. Return the head of the resulting list.

Example 1

Input: head = [1,2,3,3,4,4,5]

Output: [1,2,5]

The values 3 and 4 each occur twice, so all of their nodes are removed, leaving only 1, 2, and 5.

Example 2

Input: head = [1,1,1,2,3]

Output: [2,3]

The value 1 repeats three times and is dropped entirely, while 2 and 3 appear once and survive.

Constraints

  • The number of nodes in the list is in the range [0, 300].
  • -100 <= Node.val <= 100
  • The list is guaranteed to be sorted in non-decreasing order.
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now