Skip to content

Latest commit

 

History

History

82-RemoveDuplicatesfromSortedListII

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 

Remove Duplicates from Sorted List II

Problem can be found in here!

# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

Solution: Two Pointers

def deleteDuplicates(head: Optional[ListNode]) -> Optional[ListNode]:
    previous_node = dummy_head = ListNode(0, head)
    while head:
        if head.next and head.val == head.next.val:
            while head.next and head.val == head.next.val:
                head = head.next
            previous_node.next = head.next
        else:
            previous_node = previous_node.next
        head = head.next

    return dummy_head.next

Time Complexity: O(n), Space Complexity: O(1).