Remove Duplicates from Sorted List — LeetCode 83 Python Solution
EasyLinked List
- Problem
- #83
- Pattern
- Linked List
- Reading time
- 2 min
- Source
- leetcode.com
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 headComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the linked list |
| Space | O(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.