Skip to main content

83. Remove Duplicates from Sorted List

easy

Collapse consecutive duplicates in a sorted singly linked list into single occurrences. A one-pass pointer-skip drill that warms you up for the harder variant (82) where every duplicated value vanishes entirely.

By Sam K., Founder, InterviewChamp.AI · Last verified

Problem

Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.

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 ascending order.

Examples

Example 1

Input
head = [1,1,2]
Output
[1,2]

Example 2

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

Example 3

Input
head = []
Output
[]

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Hints

Progressive — try the first before opening the next.

Hint 1

Because the list is sorted, every group of duplicates is contiguous.

Hint 2

Walk the list with a single pointer. While the next node has the same value as the current node, bypass it by setting current.next = current.next.next.

Hint 3

Only advance current when current.next has a different value — otherwise you'd skip past a real new value.

Solution approach

Reveal approach

Single-pointer in-place skip. Use one pointer current starting at head. Loop while current and current.next are both non-null: if current.val == current.next.val, rewire current.next = current.next.next (skipping the duplicate without advancing current, because the new next might also be a duplicate). Otherwise, advance current = current.next. Return head — no dummy needed because the head itself is the first occurrence and is never removed. O(n) time, O(1) extra space.

Complexity

Time
O(n)
Space
O(1)

Related patterns

  • linked-list
  • pointer-rewiring
  • in-place-mutation

Related problems

Asked at

Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).

  • Amazon
  • Microsoft
  • Apple

More Linked Lists practice problems

See all Linked Lists problems →