< Back





1721. Swapping Nodes in a Linked List

The solution is as follows:


  class Solution:
      def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
          dummy = curr = ListNode(-1, head)

          while curr:
              if curr.next and curr.next.next and curr.next.val == curr.next.next.val:
                  dup = curr.next.val

                  while curr.next and curr.next.val == dup:
                      curr.next = curr.next.next
              else:
                  curr = curr.next

          return dummy.next


_ Time Complexity:

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

_ Space Complexity:

  O(1) - We maintain pointers that occupy constant space.