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
Iterate Through the Linked List:
Start with the head of the linked list.
Use a pointer (
current
) to traverse the list.
Check for Duplicates:
While the current node and the next node exist, compare their values:
If the value of
current.next
is equal tocurrent.val
, skip the next node by settingcurrent.next
tocurrent.next.next
.Otherwise, move the
current
pointer to the next node.
Continue Until the End:
- Repeat the process until all duplicates are removed.
Return the Modified List:
- At the end of the traversal, return the modified linked list starting from
head
.
- At the end of the traversal, return the modified linked list starting from
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
Input:
head = [1, 1, 2]
Output:[1, 2]
Explanation: The duplicate1
is removed.Input:
head = [1, 1, 2, 3, 3]
Output:[1, 2, 3]
Explanation: The duplicates1
and3
are removed.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. 😊