SDE & MLE Prep

82. Remove Duplicates from Sorted List II

Problem

The linked list is sorted. Delete every node whose value appears more than once, leaving only values that were unique, and return the head.

Example: 1→2→3→3→4→4→5 → 1→2→5; 1→1→1→2→3 → 2→3

Remove every value that repeats. With a dummy, prev points to the last kept node; if the run starting at prev.next has length > 1, skip the whole run.

Complexity: O(n).

class Solution:
    def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
        dummy = prev = ListNode(0, head)
        while prev.next:
            cur = prev.next
            if cur.next and cur.next.val == cur.val:
                while cur.next and cur.next.val == cur.val:
                    cur = cur.next
                prev.next = cur.next          # drop the whole run
            else:
                prev = cur
        return dummy.next