< Back





83. Remove Duplicates from Sorted List

We've got a sorted linked list but it contains duplicates. We need to remove the duplicates from
the linked list and return it sorted. Luckily for us, it's already sorted so we just have to remove
the duplicates.

To remove the duplicates, we keep track of a current pointer. While the current pointer and its
.next node are valid, we check to see if the .next node's value is equal to the current node's value.
If it is, we unlink it, setting the current pointer's next node to the .next node's .next node.
Othwerwise, we move the current pointer to the next node.

The solution is as follows:


  class Solution:
      def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
          if not head: return head
          
          dummy = head
          
          while dummy and dummy.next:
              if dummy.val == dummy.next.val:
                  dummy.next = dummy.next.next
              else:
                  dummy = dummy.next
                  
          return head


_ Time Complexity:

  O(n) - We traverse all nodes within the linked list.

_ Space Complexity:

  O(1) - We maintain one pointer.