← Back to Leo Academy Masterclass

Problem #82: Remove Duplicates from Sorted List II

Medium Linked List

Intuition & Strategy Breakdown

Use a dummy node before head. Iterate through the list; if adjacent nodes have duplicate values, skip all nodes with that value until reaching a distinct node.

Python Solution

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

Java Solution

class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        ListNode dummy = new ListNode(0, head);
        ListNode prev = dummy;

        while (head != null) {
            if (head.next != null && head.val == head.next.val) {
                while (head.next != null && head.val == head.next.val) {
                    head = head.next;
                }
                prev.next = head.next;
            } else {
                prev = prev.next;
            }
            head = head.next;
        }
        return dummy.next;
    }
}
Watch Interactive Video on Leo Academy Main App