#82
Remove Duplicates from Sorted List II
MediumLinked ListTwo PointersTwo PointersLinked List Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
This approach uses a dummy node and a single pass through the list to efficiently remove duplicates. By keeping track of the previous node, we can easily skip over duplicates without needing nested loops.
⚙️
Algorithm
6 steps- 1Step 1: Create a dummy node that points to the head of the list.
- 2Step 2: Initialize two pointers: prev (to track the last unique node) and current (to traverse the list).
- 3Step 3: Traverse the list while checking for duplicates.
- 4Step 4: If duplicates are found, skip all of them by advancing current.
- 5Step 5: If no duplicates are found, move prev to current.
- 6Step 6: Continue until the end of the list and return dummy.next.
solution.py20 lines
1# Full working Python code
2class ListNode:
3 def __init__(self, val=0, next=None):
4 self.val = val
5 self.next = next
6
7def deleteDuplicates(head):
8 dummy = ListNode(0)
9 dummy.next = head
10 prev = dummy
11 current = head
12 while current:
13 if current.next and current.val == current.next.val:
14 while current.next and current.val == current.next.val:
15 current = current.next
16 prev.next = current.next
17 else:
18 prev = prev.next
19 current = current.next
20 return dummy.nextℹ
Complexity note: This complexity is linear because we only traverse the list once, making it much more efficient than the brute force approach.
- 1The linked list is sorted, which allows us to easily identify duplicates by comparing adjacent nodes.
- 2Using a dummy node simplifies edge cases, such as when the head itself is a duplicate.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.