Remove Duplicates from Sorted List II

Medium

Topics
Linked ListTwo Pointers

Given the head of a sorted linked list, delete all nodes that have duplicate values, leaving only values that appear exactly once. Return the sorted list.

Example 1

1233445null
removed entirely
Unlike the first version, a duplicated value is removed completely rather than reduced to one copy. Since the head itself can disappear, a dummy node before the list saves special-casing it, and the pointer being advanced is the last node known to be unique.
Linked list values from head to tail.
Input:  head = [1,2,3,3,4,4,5]
Output: [1,2,5]

Example 2

11123null
removed entirely
Input:  head = [1,1,1,2,3]
Output: [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

Sortedness means every group of equal values is one contiguous run, so "appears more than once" is a local property you can decide by looking at neighbours. The job is to skip whole runs, not individual nodes.

The awkward part is that the node before a deleted run has to be relinked, and that node may be the head. A dummy node in front removes the special case entirely. Keep prev pointing at the last node known to be kept, advance cur to the end of its run, and then decide: if cur never moved the run had length one, so keep it; otherwise splice the whole run out.

Approach

  1. Create a dummy whose next is the head, with prev at the dummy and cur at the head.
  2. Advance cur while cur.next holds the same value, landing on the last node of the run.
  3. If prev.next == cur the run was a single node, so move prev forward.
  4. Otherwise set prev.next = cur.next, dropping the run.
  5. Advance cur and repeat.

Dry Run

input  1 -> 2 -> 3 -> 3 -> 4 -> 4 -> 5

run [1]      prev.next == cur, length 1   keep, prev moves to 1
run [2]      prev.next == cur, length 1   keep, prev moves to 2
run [3,3]    prev.next != cur             splice out, prev stays at 2
run [4,4]    prev.next != cur             splice out, prev stays at 2
run [5]      prev.next == cur, length 1   keep

answer  1 -> 2 -> 5

edge cases, verified
  [1,1,1,2,3]  ->  2 -> 3        the head itself is deleted
  [1,1]        ->  empty list
  []           ->  empty list

Complexity

  • Time — O(n): each node is passed once; the inner run-walk advances the same cur that the outer loop uses, so it is not nested work.
  • Space — O(1): one dummy and two pointers.

Common Pitfalls

  • Working without a dummy node. Every run that includes the head then needs its own branch, which is where this problem is usually failed.
  • Deleting only the extra copies and keeping one, which is remove duplicates I. Here a value that appears twice disappears completely.
  • Comparing cur.val with prev.val to detect a run. prev points into the kept list, which may be far away; the run is detected by looking forward at cur.next.
  • Advancing prev unconditionally. It must stay put whenever a run was removed, because the node it points at is still the last kept node.
  • Assuming the algorithm works on unsorted input. It relies on equal values being adjacent; given [1,2,2,1] it removes the adjacent pair and returns 1 -> 1, which is correct for the run-based rule but not what "appears exactly once" would mean globally.

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):
        dummy = ListNode(0, head)
        prev = dummy
        cur = head
        while cur:
            while cur.next and cur.val == cur.next.val:
                cur = cur.next
            if prev.next == cur:
                prev = prev.next
            else:
                prev.next = cur.next
            cur = cur.next
        return dummy.next
SensAI
Beta
Tap the mic to stop voice mode