GFG POTD - Remove all occurences of duplicates in a linked list
Given a sorted linked list, delete all nodes that have duplicate numbers (all occurrences), leaving only numbers that appear once in the original list, and return the head of the modified linked list.
Examples:
Input: Linked List = 23->28->28->35->49->49->53->53
Output: 23 35
Explanation: The duplicate numbers are 28, 49 and 53 which are removed from the list.
Input: Linked List = 11->11->11->11->75->75
Output: Empty list
Explanation: All the nodes in the linked list have duplicates. Hence the resultant list would be empty.
Expected Time Complexity: O(n)
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ size(list) ≤ 105
Solution
The Solution
class contains the method removeAllDuplicates
which takes the head of the linked list as input and returns the head of the modified list. In our solution:
A dummy
node is created to handle edge cases (e.g., when the head node itself needs to be removed). dummy->next
points to the original head of the list.
prev
is a pointer to the last node that is not a duplicate. Initially, it points to the dummy
node.
current
is a pointer used to traverse the linked list. Initially, it points to the head of the list.
Node* dummy = new Node(0);
dummy->next = head;
Node* prev = dummy;
Node* current = head;
while(current){
bool isDup = false;
while(current->next && current->data == current->next->data){
current = current->next;
isDup = true;
}
if(isDup){
prev->next = current->next;
} else{
prev = prev->next;
}
current = current->next;
}
The outer
while
loop continues as long ascurrent
is notnullptr
.The inner
while
loop checks for duplicates. Ifcurrent
andcurrent->next
have the samedata
, it movescurrent
tocurrent->next
and setsisDuplicate
totrue
.After the inner loop, if duplicates were found (
isDuplicate
istrue
),prev->next
is updated tocurrent->next
, effectively skipping all nodes with the duplicated value.If no duplicates were found,
prev
is moved toprev->next
.current
is then moved tocurrent->next
to continue traversal.After the traversal, the modified list starts from
dummy->next
.The
dummy
node is deleted to free memory.The method returns
dummy->next
, which is the head of the modified list.
Node* result = dummy->next;
delete dummy;
return result;
Below is the entire code:
class Solution {
public:
Node* removeAllDuplicates(struct Node* head) {
Node* dummy = new Node(0);
dummy->next = head;
Node* prev = dummy;
Node* current = head;
while(current){
bool isDup = false;
while(current->next && current->data == current->next->data){
current = current->next;
isDup = true;
}
if(isDup){
prev->next = current->next;
} else{
prev = prev->next;
}
current = current->next;
}
Node* result = dummy->next;
delete dummy;
return result;
}
};
Thank you ! Keep Learning :)