Remove Duplicates from Sorted List II — LeetCode 82 Python Solution

MediumLinked ListTwo Pointers
Problem
#82
Reading time
3 min

The problem

Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.

Example

Input
head = [1,2,3,3,4,4,5]
Output
[1,2,5]

Python solution

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]:
        dummy = pre = ListNode(next=head)
        cur = head
        while cur:
            while cur.next and cur.next.val == cur.val:
                cur = cur.next
            if pre.next == cur:
                pre = cur
            else:
                pre.next = cur.next
            cur = cur.next
        return dummy.next

Complexity

MeasureComplexity
TimeO(n)
SpaceO(1) auxiliary

Pattern: Linked List

Rewire pointers in place, with a dummy head and a saved next to keep it safe. LeetCode 82. Remove Duplicates from Sorted List II is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Linked List.

The linked list guide has the Python template for the pattern and the 75 LeetCode problems that use it.

Related problems

On a study list

This problem is on Top Interview 150.

Frequently asked questions

How hard is LeetCode 82. Remove Duplicates from Sorted List II?
LeetCode 82. Remove Duplicates from Sorted List II is rated Medium on LeetCode.
What is the time complexity of LeetCode 82. Remove Duplicates from Sorted List II?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 82. Remove Duplicates from Sorted List II?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 82. Remove Duplicates from Sorted List II cover?
LeetCode 82. Remove Duplicates from Sorted List II is tagged Linked List and Two Pointers on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview