November 21, 2024
The trick for this one was tracking duplicates via the unique boolean and a pending variable.
1# Definition for singly-linked list.2# class ListNode:3# def __init__(self, val=0, next=None):4# self.val = val5# self.next = next6class Solution:7 def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:8 start = None9 curr = None10 pending = None11 unique = True12 while head:13 if not pending:14 pending = head15 elif pending.val != head.val and unique:16 if not start:17 start = pending18 curr = start19 else:20 curr.next = pending21 curr = curr.next22 pending = head23 elif pending.val != head.val and not unique:24 pending = head25 unique = True26 else:27 unique = False28 if curr:29 curr.next = None30 head = head.next3132 if pending and unique:33 if start:34 curr.next = pending35 else:36 start = pending3738 return start
Time complexity is O(n) = n and space complexity is O(1).
LeetCode 100. Same Tree
LeetCode 86. Partition List