Straightforward O(N) time and space Python solution with comments

  • 0
    def deleteDuplicates(self, head):
        """ We want to generate a valid linked list from the current given list. 
            Because the given list is sorted,  the valid node only need to satisfy 
            having different value with the node before and the one after.
        new = curr = ListNode(None)
        repeat = None
        while head:
            # Having the same value as the node after it
            if and head.val ==
                repeat = head.val
                head =
            # Having the same value as the node before it         
            elif head.val == repeat:
                head =
            # Valid node
       = ListNode(head.val)
                curr =
                head =

Log in to reply

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