Given a head of an unsorted linked list. Remove duplicate elements from this unsorted Linked List. When a value appears in multiple nodes, the node which appeared first should be kept, all other duplicates are to be removed.
Examples:
Input: head = 5 -> 2 -> 2 -> 4 Output: 5 -> 2 -> 4 Explanation: Given linked list elements are 5 -> 2 -> 2 -> 4, in which 2 is repeated only. So, we will delete the extra repeated elements 2 from the linked list and the resultant linked list will contain 5->2->4.
Input: head = 2 -> 2 -> 2 -> 2 -> 2 Output: 2 Explanation: Given linked list elements are 2 -> 2 -> 2 -> 2 -> 2, in which 2 is repeated. So, we will delete the extra repeated elements 2 from the linked list and the resultant linked list will contain only 2.
[Naive Approach] Check Every Previous Node - O(n ^ 2) Time and O(1) Space
The idea is to traverse the linked list and, for every node, check all the previous nodes to see whether the current value has already appeared. If it is found, remove the current node; otherwise, keep it.
Working of Approach:
Traverse the linked list using the current node.
For each node, traverse from the head to the current node.
If the current value is found earlier, delete the current node.
Otherwise, move to the next node.
Return the modified linked list.
C++
#include<iostream>usingnamespacestd;classNode{public:intdata;Node*next;Node(intx){data=x;next=nullptr;}};// Function to remove duplicate nodes.Node*removeDuplicates(Node*head){// Return if the list is empty.if(head==nullptr)returnhead;Node*prev=head;Node*curr=head->next;// Traverse the linked list.while(curr!=nullptr){boolduplicate=false;// Check all previous nodes.Node*temp=head;while(temp!=curr){if(temp->data==curr->data){duplicate=true;break;}temp=temp->next;}// Remove duplicate node.if(duplicate){prev->next=curr->next;deletecurr;curr=prev->next;}else{prev=curr;curr=curr->next;}}returnhead;}// Function to print linked list.voidprintList(Node*head){while(head){cout<<head->data;if(head->next)cout<<" -> ";head=head->next;}cout<<endl;}intmain(){// Creating linked list:// 5 -> 2 -> 2 -> 4Node*head=newNode(5);head->next=newNode(2);head->next->next=newNode(2);head->next->next->next=newNode(4);head=removeDuplicates(head);printList(head);return0;}
Java
importjava.util.*;classNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}publicclassGFG{// Function to remove duplicate nodes.publicstaticNoderemoveDuplicates(Nodehead){// Return if the list is empty.if(head==null)returnhead;Nodeprev=head;Nodecurr=head.next;// Traverse the linked list.while(curr!=null){booleanduplicate=false;// Check all previous nodes.Nodetemp=head;while(temp!=curr){if(temp.data==curr.data){duplicate=true;break;}temp=temp.next;}// Remove duplicate node.if(duplicate){prev.next=curr.next;curr=prev.next;}else{prev=curr;curr=curr.next;}}returnhead;}// Function to print linked list.publicstaticvoidprintList(Nodehead){while(head!=null){System.out.print(head.data);if(head.next!=null)System.out.print(" -> ");head=head.next;}System.out.println();}publicstaticvoidmain(String[]args){// Creating linked list:// 5 -> 2 -> 2 -> 4Nodehead=newNode(5);head.next=newNode(2);head.next.next=newNode(2);head.next.next.next=newNode(4);head=removeDuplicates(head);printList(head);}}
Python
classNode:# Constructor to initialize the nodedef__init__(self,x):self.data=xself.next=None# Function to remove duplicate nodes.defremoveDuplicates(head):# Return if the list is empty.ifheadisNone:returnheadprev=headcurr=head.next# Traverse the linked list.whilecurrisnotNone:duplicate=False# Check all previous nodes.temp=headwhiletemp!=curr:iftemp.data==curr.data:duplicate=Truebreaktemp=temp.next# Remove duplicate node.ifduplicate:prev.next=curr.nextcurr=prev.nextelse:prev=currcurr=curr.nextreturnhead# Function to print linked list.defprintList(head):whileheadisnotNone:print(head.data,end="")ifhead.nextisnotNone:print(" -> ",end="")head=head.nextprint()if__name__=='__main__':# Creating linked list:# 5 -> 2 -> 2 -> 4head=Node(5)head.next=Node(2)head.next.next=Node(2)head.next.next.next=Node(4)head=removeDuplicates(head)printList(head)
C#
usingSystem;classNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}classGFG{// Function to remove duplicate nodes.staticNoderemoveDuplicates(Nodehead){// Return if the list is empty.if(head==null)returnhead;Nodeprev=head;Nodecurr=head.next;// Traverse the linked list.while(curr!=null){boolduplicate=false;// Check all previous nodes.Nodetemp=head;while(temp!=curr){if(temp.data==curr.data){duplicate=true;break;}temp=temp.next;}// Remove duplicate node.if(duplicate){prev.next=curr.next;curr=prev.next;}else{prev=curr;curr=curr.next;}}returnhead;}// Function to print linked list.staticvoidprintList(Nodehead){while(head!=null){Console.Write(head.data);if(head.next!=null)Console.Write(" -> ");head=head.next;}Console.WriteLine();}staticvoidMain(string[]args){// Creating linked list:// 5 -> 2 -> 2 -> 4Nodehead=newNode(5);head.next=newNode(2);head.next.next=newNode(2);head.next.next.next=newNode(4);head=removeDuplicates(head);printList(head);}}
JavaScript
classNode{constructor(x){this.data=x;this.next=null;}}// Function to remove duplicate nodes.functionremoveDuplicates(head){// Return if the list is empty.if(head===null)returnhead;letprev=head;letcurr=head.next;// Traverse the linked list.while(curr!==null){letduplicate=false;// Check all previous nodes.lettemp=head;while(temp!==curr){if(temp.data===curr.data){duplicate=true;break;}temp=temp.next;}// Remove duplicate node.if(duplicate){prev.next=curr.next;curr=prev.next;}else{prev=curr;curr=curr.next;}}returnhead;}// Function to print linked list.functionprintList(head){letoutput="";while(head!==null){output+=head.data;if(head.next!==null)output+=" -> ";head=head.next;}console.log(output);}// Driver Code// Creating linked list:// 5 -> 2 -> 2 -> 4lethead=newNode(5);head.next=newNode(2);head.next.next=newNode(2);head.next.next.next=newNode(4);head=removeDuplicates(head);printList(head);
Output
5 -> 2 -> 4
[Expected Approach] Using Hash Set - O(n) Time and O(n) Space
The idea is to traverse the linked list while storing the values that have already been seen in a hash set. If the current node's value is already present in the set, it is a duplicate, so remove that node. Otherwise, insert the value into the set and continue traversing the list.
Working of Approach:
Create an empty hash set to store the values already encountered.
Traverse the linked list from the head node.
If the current node's value is not present in the hash set, insert it and move ahead.
If the value is already present, remove the current node by updating the previous node's next pointer.
Continue until all nodes are processed and return the modified linked list.
Let us understand with an example: Input: head = 5 -> 2 -> 2 -> 4
Start with the linked list 5 -> 2 -> 2 -> 4 and an empty hash set { }. Insert 5 into the set and move to the next node.
Visit 2. Since it is not present in the hash set, insert it. The set becomes {5, 2}.
Visit the next 2. It is already present in the hash set, so it is a duplicate. Remove this node by updating the previous node's next pointer.
Move to 4. It is not present in the hash set, so insert it. The set becomes {5, 2, 4}.
The traversal ends, and the modified linked list is 5 -> 2 -> 4.
C++
#include<iostream>usingnamespacestd;classNode{public:intdata;Node*next;Node(intx){data=x;next=nullptr;}};Node*removeDuplicates(Node*head){// Return if the linked list is empty.if(!head)returnnullptr;// Using an unordered_set to keep track of seen values.unordered_set<int>seen;Node*curr=head;Node*prev=nullptr;// Iterating through the linked list.while(curr!=nullptr){// If the current value is a duplicate, remove the node.if(seen.find(curr->data)!=seen.end()){prev->next=curr->next;deletecurr;}else{// If the value is not a duplicate, add it to the set and update the// pointers.seen.insert(curr->data);prev=curr;}curr=prev->next;}returnhead;}// Function to print linked list.voidprintList(Node*head){while(head){cout<<head->data;if(head->next)cout<<" -> ";head=head->next;}cout<<endl;}intmain(){// Creating linked list:// 5 -> 2 -> 2 -> 4Node*head=newNode(5);head->next=newNode(2);head->next->next=newNode(2);head->next->next->next=newNode(4);head=removeDuplicates(head);printList(head);return0;}
Java
importjava.util.HashSet;classNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}publicclassGFG{publicstaticNoderemoveDuplicates(Nodehead){// Return if the linked list is empty.if(head==null)returnnull;// Using a HashSet to keep track of seen values.HashSet<Integer>seen=newHashSet<>();Nodecurr=head;Nodeprev=null;// Iterating through the linked list.while(curr!=null){// If the current value is a duplicate, remove// the node.if(seen.contains(curr.data)){prev.next=curr.next;curr=prev.next;}else{// If the value is not a duplicate, add it// to the set and update the pointers.seen.add(curr.data);prev=curr;}curr=prev!=null?prev.next:null;}returnhead;}// Function to print linked list.publicstaticvoidprintList(Nodehead){while(head!=null){System.out.print(head.data);if(head.next!=null)System.out.print(" -> ");head=head.next;}System.out.println();}publicstaticvoidmain(String[]args){// Creating linked list:// 5 -> 2 -> 2 -> 4Nodehead=newNode(5);head.next=newNode(2);head.next.next=newNode(2);head.next.next.next=newNode(4);head=removeDuplicates(head);printList(head);}}
Python
classNode:def__init__(self,x):self.data=xself.next=NonedefremoveDuplicates(head):# Return if the linked list is empty.ifnothead:returnNone# Using a set to keep track of seen values.seen=set()curr=headprev=None# Iterating through the linked list.whilecurrisnotNone:# If the current value is a duplicate, remove the node.ifcurr.datainseen:prev.next=curr.nextcurr=prev.nextelse:# If the value is not a duplicate, add it to the set and update the# pointers.seen.add(curr.data)prev=currcurr=prev.nextifprevelseNonereturnhead# Function to print linked list.defprintList(head):whileheadisnotNone:print(head.data,end='')ifhead.nextisnotNone:print(' -> ',end='')head=head.nextprint()if__name__=='__main__':# Creating linked list:# 5 -> 2 -> 2 -> 4head=Node(5)head.next=Node(2)head.next.next=Node(2)head.next.next.next=Node(4)head=removeDuplicates(head)printList(head)
C#
usingSystem;usingSystem.Collections.Generic;publicclassNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}publicclassGFG{publicstaticNoderemoveDuplicates(Nodehead){// Return if the linked list is empty.if(head==null)returnnull;// Using a HashSet to keep track of seen values.HashSet<int>seen=newHashSet<int>();Nodecurr=head;Nodeprev=null;// Iterating through the linked list.while(curr!=null){// If the current value is a duplicate, remove// the node.if(seen.Contains(curr.data)){prev.next=curr.next;curr=prev.next;}else{// If the value is not a duplicate, add it// to the set and update the pointers.seen.Add(curr.data);prev=curr;}curr=prev!=null?prev.next:null;}returnhead;}// Function to print linked list.publicstaticvoidprintList(Nodehead){while(head!=null){Console.Write(head.data);if(head.next!=null)Console.Write(" -> ");head=head.next;}Console.WriteLine();}publicstaticvoidMain(){// Creating linked list:// 5 -> 2 -> 2 -> 4Nodehead=newNode(5);head.next=newNode(2);head.next.next=newNode(2);head.next.next.next=newNode(4);head=removeDuplicates(head);printList(head);}}
JavaScript
classNode{constructor(x){this.data=x;this.next=null;}}functionremoveDuplicates(head){// Return if the linked list is empty.if(!head)returnnull;// Using a Set to keep track of seen values.letseen=newSet();letcurr=head;letprev=null;// Iterating through the linked list.while(curr!=null){// If the current value is a duplicate, remove the// node.if(seen.has(curr.data)){prev.next=curr.next;curr=prev.next;}else{// If the value is not a duplicate, add it to// the set and update the pointers.seen.add(curr.data);prev=curr;}curr=prev?prev.next:null;}returnhead;}// Function to print linked list.functionprintList(head){letcurrent=head;while(current!=null){process.stdout.write(current.data.toString());if(current.next!=null)process.stdout.write(" -> ");current=current.next;}console.log();}// Driver Codelethead=newNode(5);head.next=newNode(2);head.next.next=newNode(2);head.next.next.next=newNode(4);head=removeDuplicates(head);printList(head);