Python Simple O(n) Time O(1) space


  • 0

    Similar to Remove Duplicates from Sorted List I (duh) but now we just need to check against both the previous value as well as the next value. Keep track of previous value in a variable and use that to check if duplicate or not.

        def deleteDuplicates(self, head):
    
            buffr = prev = ListNode(None)
            buffr.next = itr = head
            val = None
            while itr:
                nxt = itr.next
                if itr.val == val or (itr.next and itr.next.val == itr.val):
                    prev.next, itr.next = itr.next, None
                else:
                    prev = itr
                itr, val = nxt, itr.val # move pointer forward and update previous val
            return buffr.next
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.