Efficient Solution to Remove Duplicates from Sorted Linked List in Python.

Efficient Solution to Remove Duplicates from Sorted Linked List in Python.

Intuition

The problem requires removing duplicate nodes from a sorted linked list. Since the list is already sorted, duplicate values will always appear consecutively. Therefore, we can traverse the list once, compare the current node with the next node, and remove duplicates as we go.


Approach

  1. Iterate Through the Linked List:

    • Start with the head of the linked list.

    • Use a pointer (current) to traverse the list.

  2. Check for Duplicates:

    • While the current node and the next node exist, compare their values:

  3. Continue Until the End:

    • Repeat the process until all duplicates are removed.
  4. Return the Modified List:

    • At the end of the traversal, return the modified linked list starting from head.

Complexity

  • Time Complexity:
    $$O(n)$$
    We traverse the entire linked list once, where (n) is the number of nodes in the list.

  • Space Complexity:
    $$O(1)$$
    No additional space is used; the list is modified in place.


Code

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

class Solution(object):
    def deleteDuplicates(self, head):
        current = head

        while current:
            while current.next and current.next.val == current.val:
                current.next = current.next.next
            current = current.next

        return head

Example Test Cases

  1. Input: head = [1, 1, 2]
    Output: [1, 2]
    Explanation: The duplicate 1 is removed.

  2. Input: head = [1, 1, 2, 3, 3]
    Output: [1, 2, 3]
    Explanation: The duplicates 1 and 3 are removed.

  3. Input: head = []
    Output: []
    Explanation: An empty list remains empty.


Connect with Me

If you found this solution helpful, feel free to connect with me on LinkedIn! Let’s grow and share knowledge together. 😊


Did you find this article valuable?

Support VISHWANATH'S BLOG by becoming a sponsor. Any amount is appreciated!