AlgoMaster Logo

Remove Duplicates from Sorted List II

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Two Pointers with Dummy Node

Intuition:

In this problem, we are dealing with a sorted linked list. The goal is to remove all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

  • The sorted nature of the list allows us to detect duplicates by simply comparing adjacent nodes.
  • To handle edge cases, like a head that needs to be removed because it's duplicated, we can use a dummy node. A dummy node is a temporary node that helps simplify edge case handling, such as head deletion.
  • By using two pointers, prev and current, we can manage list traversal and modification efficiently.

Steps:

  1. Initialize a dummy node that points to the head of the linked list.
  2. Use a pointer prev to track the last node before the sequence of duplicates.
  3. Use another pointer current to iterate through the list.
  4. For each node, compare it with the next node to check if it's a start of a duplicate sequence.
  5. When a series of duplicates is detected, prev’s next is linked to the node after the duplicates.
  6. If no duplicates are found, simply move prev to current.
  7. Continue this process until the end of the list.
  8. Finally, return dummy.next because dummy was pointing to the beginning of the list structure we have built.

Code: