DEV Community

Navin S
Navin S

Posted on

๐Ÿ”— Remove Duplicates from a Sorted Linked List

Removing duplicates from a linked list is a common problem that helps you understand pointer traversal and in-place modification.


๐Ÿ“Œ Problem Statement

Given the head of a sorted linked list, remove all duplicate elements so that each value appears only once.

Return the updated linked list.


๐Ÿ” Example

Input:
2 โ†’ 2 โ†’ 2 โ†’ 2

Output:
2


๐Ÿง  Intuition

Since the list is already sorted:

๐Ÿ‘‰ Duplicate elements will always be next to each other

So we can:

  • Compare current node with next node
  • Skip duplicates by adjusting pointers

๐Ÿ”„ Approach (Iterative)

Step-by-Step:

  1. Start from the head
  2. Traverse the list
  3. If current value equals next value:
  • Skip the next node

    1. Else:
  • Move forward


๐Ÿ’ป Python Code

```python id="dup1"
class ListNode:
def init(self, val=0, next=None):
self.val = val
self.next = next

def delete_duplicates(head):
current = head

while current and current.next:
    if current.val == current.next.val:
        current.next = current.next.next  # skip duplicate
    else:
        current = current.next

return head
Enter fullscreen mode Exit fullscreen mode



---

๐Ÿงพ Dry Run

For:
2 โ†’ 2 โ†’ 2 โ†’ 2

Steps:

* Compare first two โ†’ same โ†’ skip
* Compare next โ†’ same โ†’ skip
* Continue until only one node remains

Final:
2

---

โšก Complexity

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

---

๐Ÿ”ฅ Why This Works

* Sorted property ensures duplicates are adjacent
* Only one traversal needed
* No extra space used

---

โš ๏ธ Edge Cases

* Empty list
* Single node
* All elements same

---

๐Ÿ Conclusion

This problem teaches:

* Pointer manipulation
* Efficient traversal
* In-place linked list operations
Enter fullscreen mode Exit fullscreen mode

Top comments (0)