Given the head of a sorted singly linked list, remove all duplicate nodes so that each element appears only once. The resulting linked list should remain sorted.
Note: Try to solve the problem without using extra space
Examples:
Input: Head: 2->2->4->5 Output: 2 -> 4 -> 5
Explanation: In the given linked list 2 -> 2 -> 4 -> 5, only 2 occurs more than 1 time. So we need to remove it once.
Input: Head: 2->2->2->2->2 Output: 2
Explanation: In the given linked list 2 -> 2 -> 2 -> 2, 2 is the only element and is repeated 5 times. So we need to remove any four 2.
[Naive Approach] Hash Set – O(n) Time and O(n) Space
The idea is to traverse the linked list and check if the value is present in Hash Set or not.
If the value is not present in the Hash Set then push the value in Hash Set append the nodes in the new list , otherwise skip the value as it is the duplicate value.
Working of Approach:
Initialize an empty Hash Set and pointers new_head and tail as NULL.
Iterate through the original list, adding each unique node's value to the Hash Set and appending the node to the new list.
Return the new_head of the new list with duplicates removed.
C++
#include<iostream>usingnamespacestd;classNode{public:intdata;Node*next;Node(intx){data=x;next=nullptr;}};Node*removeDuplicates(Node*head){// Unordered map to track unique node valuesunordered_set<int>st;// Initialize pointers for traversing the original list// and building the new list without duplicatesNode*new_head=nullptr;Node*tail=nullptr;// Traverse the original listNode*curr=head;while(curr!=nullptr){// Check if the current node's data is not in the mapif(st.find(curr->data)==st.end()){// Create a new node for the unique dataNode*new_node=newNode(curr->data);// If new_head is null, this is the// first unique nodeif(new_head==nullptr){new_head=new_node;tail=new_head;}else{// Append the new node to the end// of the new listtail->next=new_node;tail=new_node;}// Mark this data as encounteredst.insert(curr->data);}// Move to the next node in the original listcurr=curr->next;}// delete old listcurr=head;while(curr!=nullptr){Node*temp=curr;curr=curr->next;deletetemp;}// Return the head of the new list with// duplicates removedreturnnew_head;}voidprintList(Node*node){while(node!=NULL){cout<<node->data<<" ";node=node->next;}cout<<endl;}intmain(){// Create a sorted linked list// 11->11->11->13->13->20Node*head=newNode(11);head->next=newNode(11);head->next->next=newNode(11);head->next->next->next=newNode(13);head->next->next->next->next=newNode(13);head->next->next->next->next->next=newNode(20);printList(head);head=removeDuplicates(head);printList(head);return0;}
Java
importjava.io.*;importjava.util.HashSet;classNode{intdata;Nodenext;Node(intx){data=x;next=null;}}classGFG{// Function to remove duplicatesstaticNoderemoveDuplicates(Nodehead){// HashSet to track unique node valuesHashSet<Integer>st=newHashSet<>();// Initialize pointers for traversing// the original list and building the new// list without duplicatesNodetemp=head;NodenewHead=null;Nodetail=null;// Traverse the original listwhile(temp!=null){// Check if the current node's data is not in// the setif(!st.contains(temp.data)){// Create a new node for the unique dataNodenewNode=newNode(temp.data);// If newHead is null, this is the first// unique nodeif(newHead==null){newHead=newNode;tail=newHead;}else{// Append the new node to the// end of the new listtail.next=newNode;tail=newNode;}// Mark this data as encounteredst.add(temp.data);}// Move to the next node in the original listtemp=temp.next;}// Return the head of the new list with// duplicates removedreturnnewHead;}// Function to print nodes in a given linked listpublicstaticvoidprintList(Nodenode){while(node!=null){System.out.print(node.data+" ");node=node.next;}System.out.println();}publicstaticvoidmain(String[]args){// Create a sorted linked list:// 11->11->11->13->13->20Nodehead=newNode(11);head.next=newNode(11);head.next.next=newNode(11);head.next.next.next=newNode(13);head.next.next.next.next=newNode(13);head.next.next.next.next.next=newNode(20);printList(head);head=removeDuplicates(head);printList(head);}}
Python
classNode:def__init__(self,x):self.data=xself.next=NonedefremoveDuplicates(head):# Set to track unique node valuesst=set()# Initialize pointers for traversing# the original list and building the # new list without duplicatestemp=headnew_head=Nonetail=None# Traverse the original listwhiletemp:# Check if the current node's data# is not in the setiftemp.datanotinst:# Create a new node for the unique datanew_node=Node(temp.data)# If new_head is None, this is the #first unique nodeifnew_headisNone:new_head=new_nodetail=new_headelse:# Append the new node to the end#of the new listtail.next=new_nodetail=new_node# Mark this data as encounteredst.add(temp.data)# Move to the next node in the original listtemp=temp.next# Return the head of the new list with#duplicates removedreturnnew_headdefprint_list(node):whilenode:print(node.data,end=" ")node=node.nextprint()if__name__=="__main__":# Create a sorted linked list:# 11->11->11->13->13->20head=Node(11)head.next=Node(11)head.next.next=Node(11)head.next.next.next=Node(13)head.next.next.next.next=Node(13)head.next.next.next.next.next=Node(20)print_list(head)head=removeDuplicates(head)print_list(head)
C#
usingSystem;usingSystem.Collections.Generic;publicclassNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}classGFG{// Function to remove duplicatesstaticNoderemoveDuplicates(Nodehead){// HashSet to track unique node valuesHashSet<int>st=newHashSet<int>();// Initialize pointers for traversing the original// list and building the new list without duplicatesNodetemp=head;NodenewHead=null;Nodetail=null;// Traverse the original listwhile(temp!=null){// Check if the current node's data// is not in the setif(!st.Contains(temp.data)){// Create a new node for the unique dataNodenewNode=newNode(temp.data);// If newHead is null, this is the// first unique nodeif(newHead==null){newHead=newNode;tail=newHead;}else{// Append the new node to the end// of the new listtail.next=newNode;tail=newNode;}// Mark this data as encounteredst.Add(temp.data);}// Move to the next node in the// original listtemp=temp.next;}// Return the head of the new listreturnnewHead;}staticvoidPrintList(Nodenode){while(node!=null){Console.Write(node.data+" ");node=node.next;}Console.WriteLine();}staticvoidMain(){// Create a sorted linked list:// 11->11->11->13->13->20Nodehead=newNode(11);head.next=newNode(11);head.next.next=newNode(11);head.next.next.next=newNode(13);head.next.next.next.next=newNode(13);head.next.next.next.next.next=newNode(20);PrintList(head);head=removeDuplicates(head);PrintList(head);}}
JavaScript
classNode{constructor(x){this.data=x;this.next=null;}}functionremoveDuplicates(head){// Set to track unique node valuesconstst=newSet();// Initialize pointers for traversing the original list// and building the new list without duplicateslettemp=head;letnewHead=null;lettail=null;// Traverse the original listwhile(temp!==null){// Check if the current node's// data is not in the setif(!st.has(temp.data)){// Create a new node for the unique dataconstnewNode=newNode(temp.data);// If newHead is null, this is the first// unique nodeif(newHead===null){newHead=newNode;tail=newHead;}else{// Append the new node to the end of// the new listtail.next=newNode;tail=newNode;}// Mark this data as encounteredst.add(temp.data);}// Move to the next node in the original listtemp=temp.next;}// Return the head of the new list with// duplicates removedreturnnewHead;}functionprintList(node){letcurrent=node;while(current){process.stdout.write(current.data+" ");current=current.next;}console.log();}// Create a sorted linked list:// 11->11->11->13->13->20lethead=newNode(11);head.next=newNode(11);head.next.next=newNode(11);head.next.next.next=newNode(13);head.next.next.next.next=newNode(13);head.next.next.next.next.next=newNode(20);printList(head);head=removeDuplicates(head);printList(head);
Output
11 11 11 13 13 20
11 13 20
[Expected Approach] Changing Next Pointers – O(n) Time and O(1) Space
The idea is to traverse the linked list and for each node, if the next node has the same data, skip and delete the duplicate node.
Working of Approach:
Traverse the linked list starting from the head node.
Iterate through the list, comparing each node with the next node.
If the data in the next node is same as the curr node adjust pointers to skip the next node.
C++
#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*next;Node(intx){data=x;next=nullptr;}};Node*removeDuplicates(Node*head){Node*curr=head;// Traverse the listwhile(curr!=NULL&&curr->next!=NULL){// Check if next value is same as currentif(curr->data==curr->next->data){Node*temp=curr->next;curr->next=curr->next->next;deletetemp;}elsecurr=curr->next;}returnhead;}intmain(){// Create a sorted linked list// 11->11->11->13->13->20Node*head=newNode(11);head->next=newNode(11);head->next->next=newNode(11);head->next->next->next=newNode(13);head->next->next->next->next=newNode(13);head->next->next->next->next->next=newNode(20);// Original listNode*temp=head;while(temp!=NULL){cout<<temp->data<<" ";temp=temp->next;}cout<<endl;head=removeDuplicates(head);// list withn no duplicatestemp=head;while(temp!=NULL){cout<<temp->data<<" ";temp=temp->next;}return0;}
C
#include<stdio.h>structNode{intdata;structNode*next;};// Function to remove duplicatesstructNode*removeDuplicates(structNode*head){structNode*curr=head;// Traverse the listwhile(curr!=NULL&&curr->next!=NULL){// Check if next value is the same as currif(curr->data==curr->next->data){structNode*temp=curr->next;curr->next=curr->next->next;free(temp);}elsecurr=curr->next;}returnhead;}structNode*createNode(intnew_data){structNode*new_node=(structNode*)malloc(sizeof(structNode));new_node->data=new_data;new_node->next=NULL;returnnew_node;}intmain(){// Create a sorted linked list:// 11->11->11->13->13->20structNode*head=createNode(11);head->next=createNode(11);head->next->next=createNode(11);head->next->next->next=createNode(13);head->next->next->next->next=createNode(13);head->next->next->next->next->next=createNode(20);// original liststructNode*temp=head;while(temp!=NULL){printf("%d ",temp->data);temp=temp->next;}printf("\n");head=removeDuplicates(head);// list with no duplicatestemp=head;while(temp!=NULL){printf("%d ",temp->data);temp=temp->next;}printf("\n");return0;}
Java
importjava.io.*;classNode{intdata;Nodenext;Node(intx){data=x;next=null;}}classGFG{// Function to remove duplicatesstaticNoderemoveDuplicates(Nodehead){Nodecurr=head;// Traverse the listwhile(curr!=null&&curr.next!=null){// Check if next value is the same as currif(curr.data==curr.next.data){NodenextNext=curr.next.next;curr.next=nextNext;}else{curr=curr.next;}}returnhead;}// Driver codepublicstaticvoidmain(String[]args){// Create a sorted linked list:// 11->11->11->13->13->20Nodehead=newNode(11);head.next=newNode(11);head.next.next=newNode(11);head.next.next.next=newNode(13);head.next.next.next.next=newNode(13);head.next.next.next.next.next=newNode(20);Nodetemp=head;while(temp!=null){System.out.print(temp.data+" ");temp=temp.next;}System.out.println();head=removeDuplicates(head);// listwith no duplicatetemp=head;while(temp!=null){System.out.print(temp.data+" ");temp=temp.next;}}}
Python
classNode:def__init__(self,x):self.data=xself.next=NonedefremoveDuplicates(head):curr=head# Traverse the listwhilecurrandcurr.next:# Check if next value is the same as currifcurr.data==curr.next.data:next_next=curr.next.nextcurr.next=next_nextelse:curr=curr.nextreturnhead# Driver codeif__name__=="__main__":# Create a sorted linked list:# 11->11->11->13->13->20head=Node(11)head.next=Node(11)head.next.next=Node(11)head.next.next.next=Node(13)head.next.next.next.next=Node(13)head.next.next.next.next.next=Node(20)# original listtemp=headwhiletemp:print(temp.data,end=" ")temp=temp.nextprint()head=removeDuplicates(head)# list with no duplicatetemp=headwhiletemp:print(temp.data,end=" ")temp=temp.nextprint()
C#
usingSystem;publicclassNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}classGFG{// Function to remove duplicatesstaticNoderemoveDuplicates(Nodehead){Nodecurr=head;// Traverse the listwhile(curr!=null&&curr.next!=null){// Check if next value is the same as currif(curr.data==curr.next.data){NodenextNext=curr.next.next;curr.next=nextNext;}else{curr=curr.next;}}returnhead;}// Driver codestaticvoidMain(){// Create a sorted linked list:// 11->11->11->13->13->20Nodehead=newNode(11);head.next=newNode(11);head.next.next=newNode(11);head.next.next.next=newNode(13);head.next.next.next.next=newNode(13);head.next.next.next.next.next=newNode(20);// original listNodetemp=head;while(temp!=null){Console.Write(temp.data+" ");temp=temp.next;}Console.WriteLine();head=removeDuplicates(head);// list with no duplicatestemp=head;while(temp!=null){Console.Write(temp.data+" ");temp=temp.next;}Console.WriteLine();}}
JavaScript
classNode{constructor(x){this.data=x;this.next=null;}}functionremoveDuplicates(head){letcurr=head;// Traverse the listwhile(curr&&curr.next){// Check if next value is the same as currif(curr.data===curr.next.data){letnextNext=curr.next.next;curr.next=nextNext;}else{curr=curr.next;}}returnhead;}// Driver code// Create a sorted linked list:// 11->11->11->13->13->20lethead=newNode(11);head.next=newNode(11);head.next.next=newNode(11);head.next.next.next=newNode(13);head.next.next.next.next=newNode(13);head.next.next.next.next.next=newNode(20);// original listlettemp=head;while(temp!==null){process.stdout.write(temp.data+" ");temp=temp.next;}console.log();head=removeDuplicates(head);// list with no duplicatestemp=head;while(temp!==null){process.stdout.write(temp.data+" ");temp=temp.next;}
Output
11 11 11 13 13 20
11 13 20
[Alternate Approach] Recursion – O(n) Time and O(n) Space
The idea is similar to the iterative approach. Here we are using the recursion to check each node and its next for duplicates.
Please note that the iterative approach would be better in terns of time and space. The recursive approach can be good fun exercise or a question in an interview / exam.
Working of Approach:
If the curr node or its next node is NULL, return the curr node.
If the current node’s data equals the next node’s data, adjust pointers to skip the duplicate.
If no duplicate, recursively process the next node.
C++
#include<iostream>usingnamespacestd;classNode{public:intdata;Node*next;Node(intnew_data){data=new_data;next=nullptr;}};Node*removeDuplicates(Node*head){if(head==NULL)returnhead;if(head->next!=NULL){if(head->data==head->next->data){Node*temp=head->next;head->next=head->next->next;deletetemp;returnremoveDuplicates(head);}else{removeDuplicates(head->next);}}returnhead;}intmain(){// Create a sorted linked list// 11->11->11->13->13->20Node*head=newNode(11);head->next=newNode(11);head->next->next=newNode(11);head->next->next->next=newNode(13);head->next->next->next->next=newNode(13);head->next->next->next->next->next=newNode(20);// Printing old listNode*temp=head;while(temp!=NULL){cout<<temp->data<<" ";temp=temp->next;}cout<<endl;removeDuplicates(head);// Printing new listtemp=head;while(temp!=NULL){cout<<temp->data<<" ";temp=temp->next;}return0;}
C
#include<stdio.h>#include<stdlib.h>typedefstructNode{intdata;structNode*next;}Node;Node*removeDuplicates(Node*head){if(head==NULL)returnhead;if(head->next!=NULL){if(head->data==head->next->data){Node*temp=head->next;head->next=head->next->next;free(temp);returnremoveDuplicates(head);}else{removeDuplicates(head->next);}}returnhead;}intmain(){// Create a sorted linked list// 11->11->11->13->13->20Node*head=(Node*)malloc(sizeof(Node));head->data=11;head->next=(Node*)malloc(sizeof(Node));head->next->data=11;head->next->next=(Node*)malloc(sizeof(Node));head->next->next->data=11;head->next->next->next=(Node*)malloc(sizeof(Node));head->next->next->next->data=13;head->next->next->next->next=(Node*)malloc(sizeof(Node));head->next->next->next->next->data=13;head->next->next->next->next->next=(Node*)malloc(sizeof(Node));head->next->next->next->next->next->data=20;head->next->next->next->next->next->next=NULL;// Printing old listNode*temp=head;while(temp!=NULL){printf("%d ",temp->data);temp=temp->next;}printf("\n");removeDuplicates(head);// Printing new listtemp=head;while(temp!=NULL){printf("%d ",temp->data);temp=temp->next;}printf("\n");return0;}
Java
classNode{intdata;Nodenext;Node(intnew_data){data=new_data;next=null;}}publicclassGFG{staticNoderemoveDuplicates(Nodehead){if(head==null)returnhead;if(head.next!=null){if(head.data==head.next.data){Nodetemp=head.next;head.next=head.next.next;temp=null;returnremoveDuplicates(head);}else{removeDuplicates(head.next);}}returnhead;}publicstaticvoidmain(String[]args){// Create a sorted linked list// 11->11->11->13->13->20Nodehead=newNode(11);head.next=newNode(11);head.next.next=newNode(11);head.next.next.next=newNode(13);head.next.next.next.next=newNode(13);head.next.next.next.next.next=newNode(20);// Printing old listNodetemp=head;while(temp!=null){System.out.print(temp.data+" ");temp=temp.next;}System.out.println();removeDuplicates(head);// Printing new listtemp=head;while(temp!=null){System.out.print(temp.data+" ");temp=temp.next;}System.out.println();}}
Python
classNode:def__init__(self,new_data):self.data=new_dataself.next=NonedefremoveDuplicates(head):ifheadisNone:returnheadifhead.nextisnotNone:ifhead.data==head.next.data:temp=head.nexthead.next=head.next.nextdeltempreturnremoveDuplicates(head)else:removeDuplicates(head.next)returnheaddefprint_list(head):temp=headwhiletempisnotNone:print(temp.data,end=' ')temp=temp.nextprint()if__name__=="__main__":# Create a sorted linked list:# 11->11->11->13->13->20head=Node(11)head.next=Node(11)head.next.next=Node(11)head.next.next.next=Node(13)head.next.next.next.next=Node(13)head.next.next.next.next.next=Node(20)print_list(head)head=removeDuplicates(head)print_list(head)
C#
usingSystem;publicclassNode{publicintdata;publicNodenext;publicNode(intnew_data){data=new_data;next=null;}}publicclassGFG{publicstaticNoderemoveDuplicates(Nodehead){if(head==null)returnhead;if(head.next!=null){if(head.data==head.next.data){Nodetemp=head.next;head.next=head.next.next;temp=null;returnremoveDuplicates(head);}else{removeDuplicates(head.next);}}returnhead;}publicstaticvoidMain(){// Create a sorted linked list// 11->11->11->13->13->20Nodehead=newNode(11);head.next=newNode(11);head.next.next=newNode(11);head.next.next.next=newNode(13);head.next.next.next.next=newNode(13);head.next.next.next.next.next=newNode(20);// Printing old listNodetemp=head;while(temp!=null){Console.Write(temp.data+" ");temp=temp.next;}Console.WriteLine();removeDuplicates(head);// Printing new listtemp=head;while(temp!=null){Console.Write(temp.data+" ");temp=temp.next;}}}
JavaScript
classNode{constructor(new_data){this.data=new_data;this.next=null;}}functionremoveDuplicates(head){if(head===null)returnhead;if(head.next!==null){if(head.data===head.next.data){lettemp=head.next;head.next=head.next.next;temp=null;returnremoveDuplicates(head);}else{removeDuplicates(head.next);}}returnhead;}// Driver Code// Create a sorted linked list// 11->11->11->13->13->20lethead=newNode(11);head.next=newNode(11);head.next.next=newNode(11);head.next.next.next=newNode(13);head.next.next.next.next=newNode(13);head.next.next.next.next.next=newNode(20);// Printing old listlettemp=head;while(temp!==null){console.log(temp.data+" ");temp=temp.next;}console.log("\n");removeDuplicates(head);// Printing new listtemp=head;while(temp!==null){console.log(temp.data+" ");temp=temp.next;}