Remove Duplicates from Sorted List
franklinqin0 Linked List
# Solution
Let be the length of the linked list.
# Iteration
As the input list is sorted, we can compare curr.val
w/ curr.next.val
. If same, skip the duplicate; otherwise, go to curr.next
.
Complexity
time:
space:
def deleteDuplicates(self, head: ListNode) -> ListNode:
curr = head
while curr and curr.next:
if curr.val == curr.next.val:
curr.next = curr.next.next
else:
curr = curr.next
return head
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# Recursion
The recursive deleteDuplicates
does not update curr
until curr.next
is the last of duplicates.
Complexity
time:
space: (due to implicit stack space)
def deleteDuplicates(self, head: ListNode) -> ListNode:
curr = head
if not curr or not curr.next: return head
if curr.val == curr.next.val:
curr.next = curr.next.next
self.deleteDuplicates(curr)
else:
self.deleteDuplicates(curr.next)
return head
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9