KatInterview

82. Remove Duplicates from Sorted List II

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem requires us to remove all nodes from a sorted linked list that have duplicate values. This means if a number appears more than once, all nodes with that value must be eliminated. Since the list is sorted, all duplicate nodes for a given value will be grouped together contiguously.

Solution

Remove Duplicates from Sorted List II in Python

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
        # Use a dummy node to simplify edge cases like removing the head.
        dummy = ListNode(0, head)
        # 'prev' is the last node before the sublist of duplicates.
        prev = dummy
        current = head

        while current:
            # Check if the current node is the start of a sequence of duplicates.
            if current.next and current.val == current.next.val:
                # Move 'current' to the last node of the duplicate sequence.
                while current.next and current.val == current.next.val:
                    current = current.next
                # Skip all the duplicate nodes by updating prev's next pointer.
                prev.next = current.next
            else:
                # If the current node is not a duplicate, move 'prev' forward.
                prev = prev.next
            
            # Move 'current' to the next node for the next iteration.
            current = current.next
            
        return dummy.next

Remove Duplicates from Sorted List II in Java

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        // Use a dummy node to handle edge cases like removing the head.
        ListNode dummy = new ListNode(0, head);
        // 'prev' is the last node before the sublist of duplicates.
        ListNode prev = dummy;
        ListNode current = head;

        while (current != null) {
            // Check if the current node is the start of a sequence of duplicates.
            if (current.next != null && current.val == current.next.val) {
                // Move 'current' to the last node of the duplicate sequence.
                while (current.next != null && current.val == current.next.val) {
                    current = current.next;
                }
                // Skip all the duplicate nodes by updating prev's next pointer.
                prev.next = current.next;
            } else {
                // If the current node is not a duplicate, move 'prev' forward.
                prev = prev.next;
            }
            // Move 'current' to the next node for the next iteration.
            current = current.next;
        }

        return dummy.next;
    }
}

Remove Duplicates from Sorted List II in C++

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        // Use a dummy node to simplify edge cases where the head is removed.
        ListNode* dummy = new ListNode(0, head);
        ListNode* prev = dummy;

        while (head != nullptr) {
            // Check if the current node is the start of a sequence of duplicates.
            if (head->next != nullptr && head->val == head->next->val) {
                // Move 'head' to the last node of the duplicate sequence.
                while (head->next != nullptr && head->val == head->next->val) {
                    head = head->next;
                }
                // Skip all the duplicate nodes by updating prev's next pointer.
                prev->next = head->next;
            } else {
                // If the current node is not a duplicate, move 'prev' forward.
                prev = prev->next;
            }
            // Move 'head' to the next node for the next iteration.
            head = head->next;
        }

        // The new list is dummy's next. We must also free the memory for the dummy node.
        ListNode* result = dummy->next;
        delete dummy;
        return result;
    }
};

Remove Duplicates from Sorted List II in TypeScript

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function deleteDuplicates(head: ListNode | null): ListNode | null {
    // Use a dummy node to handle edge cases like removing the head.
    const dummy = new ListNode(0, head);
    // 'prev' is the last node before the sublist of duplicates.
    let prev = dummy;
    let current = head;

    while (current) {
        // Check if the current node is the start of a sequence of duplicates.
        if (current.next && current.val === current.next.val) {
            // Move 'current' to the last node of the duplicate sequence.
            while (current.next && current.val === current.next.val) {
                current = current.next;
            }
            // Skip all the duplicate nodes by updating prev's next pointer.
            prev.next = current.next;
        } else {
            // If the current node is not a duplicate, move 'prev' forward.
            prev = prev.next;
        }
        // Move 'current' to the next node for the next iteration.
        current = current.next;
    }

    return dummy.next;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.