Remove Duplicates in a Un-sorted Linked List

Pattern: Traversal and dummy nodes

easy

Walk with prev from a dummy node and keep a set of values already kept. If prev.next holds a value seen before, unlink it; otherwise remember it and move on. The first copy of each value stays.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Given the head of a linked list in any order, delete every node whose value already appeared earlier, keeping the first copy of each value, and return the head. For example, 5 → 2 → 2 → 4 becomes 5 → 2 → 4, and 3 → 1 → 3 → 1 → 2 becomes 3 → 1 → 2.

This problem is from Love Babbar's 450 sheet, and this guide has no verified link for it yet. The function name removeDuplicates is this guide's own.

Think first

  • How do you know a value appeared earlier when copies can be far apart?
  • When you delete a node, which node's pointer changes?
  • Which copy should stay?

Hints

    Brute force, and why it fails

    For each node, scan the rest of the list and delete later copies: O(n²) time, O(1) memory. A hash set gives O(n) time with O(n) memory. Sorting first would lose the original order.

    The key insight

    Without sorting, the only way to know "seen before" quickly is to remember what was seen. A hash set answers that in O(1) per node.

    Dry run

    dummy0prev
    31 
    12 
    33 
    14 
    25 
    seen

    The list is 3 → 1 → 3 → 1 → 2. prev starts on a dummy, and the set is empty.

    Step 1 of 4

    The plan

    seen = empty set
    dummy.next = head, prev = dummy
    while prev.next is not null:
        if prev.next.val in seen: prev.next = prev.next.next
        else: add prev.next.val to seen; prev = prev.next
    return dummy.next
    

    Complexity

    Time
    O(n)
    Space
    O(n)

    One walk with O(1) set operations on average. The set can hold every distinct value.

    Edge cases

    • All equal: one node left.
    • All distinct: unchanged.
    • Empty list: unchanged.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public ListNode removeDuplicates(ListNode head) {
            Set<Integer> seen = new HashSet<>();
            ListNode dummy = new ListNode(0);
            dummy.next = head;
            for (ListNode prev = dummy; prev.next != null; ) {
                if (seen.add(prev.next.val)) prev = prev.next;   // first time: keep it
                else prev.next = prev.next.next;                // seen before: unlink it
            }
            return dummy.next;
        }
    }

    C++

    class Solution {
    public:
        ListNode* removeDuplicates(ListNode* head) {
            unordered_set<int> seen;
            ListNode dummy(0);
            dummy.next = head;
            for (ListNode* prev = &dummy; prev->next != NULL; ) {
                if (seen.insert(prev->next->val).second) prev = prev->next;   // first time: keep it
                else prev->next = prev->next->next;                          // seen before: unlink it
            }
            return dummy.next;
        }
    };

    Python

    from lib import ListNode
    
    class Solution:
        def removeDuplicates(self, head: ListNode) -> ListNode:
            seen = set()
            dummy = ListNode(0, head)
            prev = dummy
            while prev.next is not None:
                if prev.next.val not in seen:
                    seen.add(prev.next.val)         # first time: keep it
                    prev = prev.next
                else:
                    prev.next = prev.next.next      # seen before: unlink it
            return dummy.next

    Common mistakes

    • Moving prev after a deletion, which skips the node that slid into place.
    • Keeping the last copy instead of the first.
    • Sorting the list first, which changes the order of the survivors.

    Similar problems