Remove Duplicates from Sorted List

Easy

Topics
Linked List

Given the head of a sorted linked list, delete all duplicates so that each value appears only once. Return the sorted list.

Example 1

112null
removed duplicate
One of each value is kept, leaving 2 nodes.
Linked list values from head to tail.
Input:  head = [1,1,2]
Output: [1,2]

Example 2

11233null
removed duplicate
Input:  head = [1,1,2,3,3]
Output: [1,2,3]

Constraints

  • 0 <= number of nodes <= 300
  • -100 <= Node.val <= 100
  • The list is sorted in non-decreasing order.
Editorial — intuition, approach, complexity and pitfalls

Intuition

The list is sorted, so duplicates are consecutive. Walk once and, whenever the next node holds the same value, unlink it by pointing past it. The key detail is that after unlinking you must not advance — the new next node might also be a duplicate, as in a run of three.

No dummy head is needed here, because the first node is always kept: this problem removes duplicates but retains one copy of every value. The sibling problem that deletes all nodes of a duplicated value does need a dummy, since the head itself might go.

Approach

  1. current = head.
  2. While current and current.next exist: if their values match, splice out current.next; else advance.
  3. Return head.

Dry Run

1 -> 1 -> 2 -> 3 -> 3

cur=1, next=1  equal   -> unlink:  1 -> 2 -> 3 -> 3   (cur stays)
cur=1, next=2  differ  -> advance
cur=2, next=3  differ  -> advance
cur=3, next=3  equal   -> unlink:  1 -> 2 -> 3        (cur stays)
cur=3, next=null       -> stop

answer 1 -> 2 -> 3

Complexity

  • Time — O(n): one pass; each node is examined a constant number of times.
  • Space — O(1): one pointer. Building a new list would be O(n).

Common Pitfalls

  • Advancing after an unlink. A run of three identical values then leaves two, because the second duplicate is never compared.
  • Checking current.next.next without confirming current.next exists.
  • Using a dummy head unnecessarily — harmless, but the head can never be removed in this variant.
  • Confusing this with the "remove every duplicated value" problem, where 1 -> 1 -> 2 becomes 2 rather than 1 -> 2.

Full Solution — all languages

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class Solution:
    def deleteDuplicates(self, head):
        cur = head
        while cur and cur.next:
            if cur.next.val == cur.val:
                cur.next = cur.next.next
            else:
                cur = cur.next
        return head
SensAI
Beta
Tap the mic to stop voice mode