Remove duplicates from an unsorted linked list | Practice | GeeksforGeeks

Given an unsorted linked list of N nodes. The task is to remove duplicate elements from this unsorted Linked List. When a value appears in multiple nodes, the node which appeared first should be kept, all others duplicates are to be removed.
Example 1:
Input:
N = 4
value[] = {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

Example 2:
Input:
N = 5
value[] = {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.
Your Task:
You have to complete the method removeDuplicates() which takes 1 argument: the head of the linked list.  Your function should return a pointer to a linked list with no duplicate element.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)
Constraints:
1 <= size of linked lists <= 106
0 <= numbers in list <= 104
 
0
maac_shah3 days ago
JAVA SOLUTIONHashSet and LinkedHashSet Method checkout Both method
    public Node removeDuplicates(Node head) 
   {
        // Your code here
       HashSet<Integer> hs = new HashSet<>();
       Node cur = head;
       Node prev = null;
       
       while(cur!=null)
       {
           int curData = cur.data;
           if(hs.contains(curData))
           {
             prev.next = cur.next; 
           }
           else
           {
               hs.add(curData);
               prev = cur;
           }
           
           cur = cur.next;
       }
       
       return head;
   }
 
 
class Solution
{
    
    public Node insertAtend(Node head, int val)
    {
        Node newNode = new Node(val);
        if(head == null)
        {
            head = newNode;
            return head;
        }
        
        Node cur = head;
        while(cur!=null)
        {
            cur = cur.next;
        }
        cur.next =newNode;
        newNode.next = null;
        
        return head;
    }
    //Function to remove duplicates from unsorted linked list.
    public Node removeDuplicates(Node head) 
    {
         // Your code here
         LinkedHashSet<Integer> hs = new LinkedHashSet<>();
         Node addHead = null;
         Node cur = head;
         while(cur!=null)
         {
             hs.add(cur.data);
             cur = cur.next;
         }

        
        for(int i : hs)
        {
            System.out.print((insertAtend(addHead,i).data)+" ");
        }

         
         return addHead;
    }
}
+1
shahabuddinbravo401 week ago
 Node * removeDuplicates( Node *head)    {     unordered_set<int>s;            Node *ptr=head,*ptr1=head;           if(head!=NULL){         s.insert(ptr1->data);         ptr1=ptr1->next;     }            while(ptr1!=NULL)      {          auto it=s.find(ptr1->data);          if(it!=s.end()){              ptr1=ptr1->next;              ptr->next=ptr1;          }          else{              s.insert(ptr1->data);              ptr1=ptr1->next;              ptr=ptr->next;          }                }      return head;   }
0
gcharansaicis191 week ago
 Node * removeDuplicates( Node *head)    {   unordered_set<int> prev;   prev.insert(head->data);   struct Node* temp2 = head->next;   struct Node* temp1 = head;   while(temp2!=NULL&&temp1!=NULL)   {       if(prev.find(temp2->data)!=prev.end())       {           temp1->next = temp2->next;           temp2->next = NULL;           temp2 = temp1->next;       }       else       {              prev.insert(temp2->data);           temp1 = temp1->next;           temp2 = temp2->next;       }   }   return head;   
   }
0
ayush94602461252 weeks ago
Easy cpp solution:
 
class Solution{   public:   //Function to remove duplicates from unsorted linked list.   Node * removeDuplicates( Node *head)    {    // your code goes here    unordered_map<int,int> m;    Node *cur=head;    Node *prev=cur;    m[cur->data]=1;    cur=cur->next;    while(cur!=NULL){        if(!m[cur->data]){            m[cur->data]=1;            prev=cur;            cur=prev->next;        }else{            prev->next=cur->next;            free(cur);            cur=prev->next;        }    }return head;   }};
-1
jainmuskan5652 weeks ago
#include <bits/stdc++.h>using namespace std;
struct Node { int data; struct Node *next; Node(int x) {   data = x;   next = NULL; }};
void print(Node *root){Node *temp = root;while(temp!=NULL){cout<<temp->data<<" ";temp=temp->next;}}
// } Driver Code Ends/*The structure of linked list is the following
struct Node { int data; struct Node *next; Node(int x) {   data = x;   next = NULL; }};*/
class Solution{   public:   //Function to remove duplicates from unsorted linked list.   Node * removeDuplicates( Node *head)    {    unordered_map<int,int> m;    Node *curr=head;    Node *prev=curr;    m[curr->data]=1;    curr=curr->next;    while(curr!= NULL){        if(!m[curr->data]){            m[curr->data]= 1;           prev= curr;           curr=prev->next;                       }        else{            prev->next= curr->next;            free(curr);            curr= prev->next;           //  curr= curr->next;        }            }    return head;   }};
// { Driver Code Starts.
int main() {// your code goes hereint T;cin>>T;while(T--){ int K; cin>>K; struct Node *head = NULL;       struct Node *temp = head; for(int i=0;i<K;i++){ int data; cin>>data;  if(head==NULL)  head=temp=new Node(data);  else  {   temp->next = new Node(data);   temp=temp->next;  } }     Solution ob; Node *result  = ob.removeDuplicates(head); print(result); cout<<endl; }return 0;}  // } Driver Code Ends
0
khanchandanireet2 weeks ago
public Node removeDuplicates(Node head)    {        Set<Integer>set = new HashSet();        Node ptr = head;        set.add(ptr.data);        Node prev = head;        while(ptr.next!=null)        {            ptr=ptr.next;                        if(!set.contains(ptr.data)){                prev=prev.next;                set.add(ptr.data);            }            else{                prev.next=ptr.next;                ptr.next=null;                ptr=prev;            }        }        return head;   }
0
guptark2 weeks ago
c++ easy
 
 Node * removeDuplicates( Node *head)    {        unordered_map<int,int>m;        Node*p=head;        Node*q = NULL;        while(p!=NULL){            if(m.find(p->data)==m.end()){                m[p->data]++;                q=p;                p=p->next;            }else{                q->next = p->next;                p=q->next;            }        }        return head;   }
+1
19tuec1322 weeks ago
java solution easy
 
public Node removeDuplicates(Node head)     {       HashSet<Integer> hs=new HashSet<>();       Node tempNode1=head;       Node prev=null;       while(tempNode1!=null){           int curr=tempNode1.data;           if(hs.contains(curr)){              prev.next=tempNode1.next;           }           else{               hs.add(curr);               prev=tempNode1;           }          tempNode1=tempNode1.next;       }       return head;   }
0
bajpayeevinayak2282 weeks ago
// { Driver Code Starts ///code code code........#include <bits/stdc++.h>using namespace std;
struct Node { int data; struct Node *next; Node(int x) {   data = x;   next = NULL; }};
void print(Node *root){Node *temp = root;while(temp!=NULL){cout<<temp->data<<" ";temp=temp->next;}}
// } Driver Code Ends/*The structure of linked list is the following
struct Node { int data; struct Node *next; Node(int x) {   data = x;   next = NULL; }};*/
class Solution{   public:   //Function to remove duplicates from unsorted linked list.   Node * removeDuplicates( Node *head)    {    // your code goes here       map<int,int>umap;       umap[head->data]++;       Node *cur=head->next;       Node *prev=head;       while(cur!=NULL)       {           int z=cur->data;           if(umap[z])           {               prev->next=cur->next;               free(cur);           }           else{               umap[z]++;               prev=cur;           }           cur=cur->next;                             }       return head;   }};
// { Driver Code Starts.
int main() {// your code goes hereint T;cin>>T;while(T--){ int K; cin>>K; struct Node *head = NULL;       struct Node *temp = head; for(int i=0;i<K;i++){ int data; cin>>data;  if(head==NULL)  head=temp=new Node(data);  else  {   temp->next = new Node(data);   temp=temp->next;  } }     Solution ob; Node *result  = ob.removeDuplicates(head); print(result); cout<<endl; }return 0;}  // } Driver Code Ends
+1
sudhakarsinghbaghel1233212 weeks ago
Node* curr=head;
     map<int,int> m;
     m[head->data]++;
     while(curr ->next!=NULL)
     {
         if(m[curr->next->data])
         {
             curr->next=curr->next->next;
         }
         else
         {
             m[curr->next->data]++;
             curr=curr->next;
         }
         
     }
      return head; 
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.