#83
Remove Duplicates from Sorted List
EasyLinked ListTwo PointersLinked List
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)
The optimal solution leverages the fact that the list is already sorted. By using a single pass through the list, we can efficiently remove duplicates without needing nested loops.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a pointer to the current node starting from the head.
- 2Step 2: While the current node and its next node are not null, check if the current node's value is the same as the next node's value.
- 3Step 3: If they are the same, skip the next node by pointing the current node's next to the next node's next.
- 4Step 4: If they are different, move the current pointer to the next node.
- 5Step 5: Continue until the end of the list.
solution.py14 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 current = head
9 while current and current.next:
10 if current.val == current.next.val:
11 current.next = current.next.next
12 else:
13 current = current.next
14 return headℹ
Complexity note: This complexity is linear because we only traverse the list once, checking each node and its next node.
- 1The list is sorted, allowing for a single pass to remove duplicates.
- 2Only adjacent duplicates need to be checked.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.