Remove Duplicates from Sorted List — LeetCode 83 Python Solution

EasyLinked List
Problem
#83
Reading time
2 min

The problem

Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.

Example

Input
head = [1,1,2]
Output
[1,2]

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

Complexity

MeasureComplexity
TimeO(n), where n is the length of the linked list
SpaceO(1) auxiliary

Pattern: Linked List

Rewire pointers in place, with a dummy head and a saved next to keep it safe. LeetCode 83. Remove Duplicates from Sorted List 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

Frequently asked questions

How hard is LeetCode 83. Remove Duplicates from Sorted List?
LeetCode 83. Remove Duplicates from Sorted List is rated Easy on LeetCode.
What is the time complexity of LeetCode 83. Remove Duplicates from Sorted List?
The Python solution on this page runs in O(n), where n is the length of the linked list.
What is the space complexity of LeetCode 83. Remove Duplicates from Sorted List?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 83. Remove Duplicates from Sorted List cover?
LeetCode 83. Remove Duplicates from Sorted List is tagged Linked List 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