Remove Duplicates from Sorted List

Easy Linked List Miscellaneous

Remove Duplicates from Sorted List is a easy linked list problem solved with the miscellaneous pattern. The best approach, optimal (one pointer, compare with next), runs in O(n) time and O(1) space. Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (hash set of seen values) up.

Problem

You are given the head of a singly linked list whose values are sorted in non-decreasing order, so equal values always sit next to each other.

Delete nodes so that every value appears exactly once: of each group of equal values, keep one node and unlink the others. Return the head of the resulting list, which is still sorted.

Examples

Example 1

Input
head = [1, 1, 2]
Output
[1, 2]
Why
The two 1s sit next to each other. Keep the first one and unlink the second.

Example 2

Input
head = [1, 1, 2, 3, 3]
Output
[1, 2, 3]
Why
There are two runs of equal values, the 1s and the 3s. Each run shrinks to a single node, and 2 stays as it is.

Example 3

Input
head = []
Output
[]
Why
An empty list has nothing to remove.

Constraints

  • The list has 0 to 300 nodes.
  • -100 <= Node.val <= 100
  • The values are sorted in non-decreasing order.

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 31 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (hash set of seen values)O(n)O(n)
RecursionO(n)O(n)
Optimal (one pointer, compare with next)O(n)O(1)

1Brute force (hash set of seen values)

TimeO(n)One pass over the n nodes, with an O(1) average hash set lookup per node.
SpaceO(n)The set can hold up to n distinct values.

Ignore the sorting for a moment. Walk the list and remember every value seen so far in a hash set. A node whose value is already in the set is a copy, so link the previous kept node past it. A node with a new value is kept: add its value to the set and make it the new last kept node. This works even for an unsorted list, but it pays for the set.

  1. If head is null, return null.
  2. Put head.val in the set and let tail = head (the last kept node).
  3. For each later node p: if p.val is in the set, skip it by setting tail.next = p.next. Otherwise add p.val to the set and set tail = p.
  4. Return head.
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if (head == null) return null;
        Set<Integer> seen = new HashSet<>();
        seen.add(head.val);
        ListNode tail = head;
        for (ListNode p = head.next; p != null; p = p.next) {
            if (seen.contains(p.val)) {
                tail.next = p.next;
            } else {
                seen.add(p.val);
                tail = p;
            }
        }
        return head;
    }
}

2Recursion

TimeO(n)Each node causes exactly one call, and each call does O(1) work besides its recursive call.
SpaceO(n)The calls nest n deep before the first one returns, so the call stack holds up to n frames.

Trust the function on the rest of the list: deleteDuplicates(head.next) returns the rest with every run already shrunk to one node. That cleaned rest starts with its smallest value. If it equals head.val, the head is a copy of the node right after it, so return the cleaned rest and drop the head. Otherwise attach the cleaned rest after head and return head. An empty list or a single node is already clean.

  1. If head is null or head.next is null, return head.
  2. head.next = deleteDuplicates(head.next).
  3. If head.val == head.next.val, return head.next; otherwise return head.
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if (head == null || head.next == null) return head;
        head.next = deleteDuplicates(head.next);
        return head.val == head.next.val ? head.next : head;
    }
}

3Optimal (one pointer, compare with next)

TimeO(n)Each loop turn either removes one node or moves cur forward by one node, so there are at most n - 1 turns.
SpaceO(1)Only the single pointer cur; the list is changed in place.

Because the list is sorted, a copy is always directly after a node with the same value. Walk a single pointer cur. If cur.next holds the same value as cur, it is a copy: unlink it with cur.next = cur.next.next and do not move, because the new next node could be another copy. If the values differ, cur.next is the first node of a new value, so step onto it. When cur.next is null, every run has been shrunk to one node.

  1. cur = head.
  2. While cur != null and cur.next != null: if cur.next.val == cur.val, set cur.next = cur.next.next; else cur = cur.next.
  3. Return head.
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        ListNode cur = head;
        while (cur != null && cur.next != null) {
            if (cur.next.val == cur.val) {
                cur.next = cur.next.next;
            } else {
                cur = cur.next;
            }
        }
        return head;
    }
}

Edge cases to test

  • An empty list: return null
  • A single node: nothing to compare it with, so it comes back unchanged
  • Every node has the same value: only the head survives
  • No value repeats: the list is returned unchanged
  • A run of three or more equal values: the pointer must stay put until the whole run is gone, not jump after the first removal
  • A run at the very end of the list: the last kept node must end up pointing at null

Hints

Hint 1

The list is sorted, so all copies of a value form one block of neighbouring nodes.

Hint 2

Compare each node with the node right after it. If they hold the same value, the second one is a copy.

Hint 3

When you unlink a copy, stay on the same node: the new next node might be another copy.

FAQ

What is the best time complexity for Remove Duplicates from Sorted List?

Optimal (one pointer, compare with next) runs in O(n) time and O(1) extra space. Each loop turn either removes one node or moves cur forward by one node, so there are at most n - 1 turns.

Which pattern does Remove Duplicates from Sorted List use?

It is a linked list problem that uses the miscellaneous pattern. Other problems with the same pattern: Delete Node in a Linked List, Copy List with Random Pointer, Intersection of Two Linked Lists.

Is there a brute force solution for Remove Duplicates from Sorted List?

Yes. Brute force (hash set of seen values) takes O(n) time and O(n) space. Ignore the sorting for a moment.

Which edge cases should I test for Remove Duplicates from Sorted List?

An empty list: return null; A single node: nothing to compare it with, so it comes back unchanged; Every node has the same value: only the head survives; No value repeats: the list is returned unchanged; A run of three or more equal values: the pointer must stay put until the whole run is gone, not jump after the first removal; A run at the very end of the list: the last kept node must end up pointing at null.