[Naive Approach] Using Nested Loops - O(n^2) Time and O(1) Space
The idea is to use two nested loops. The outer loop is used to pick the elements one by one and the inner loop compares the picked element with the rest of the elements in the doubly linked list.
Below is the implementation of the above approach:
C++
// C++ program to remove duplicates from an // unsorted doubly linked list#include<iostream>usingnamespacestd;classNode{public:intdata;Node*next;Node*prev;Node(intval){data=val;next=nullptr;prev=nullptr;}};// Function to remove duplicates using nested loopsNode*removeDuplicates(Node*head){Node*curr=head;// Traverse each node in the listwhile(curr!=nullptr){Node*temp=curr;// Traverse the remaining nodes to find and // remove duplicateswhile(temp->next!=nullptr){// Check if the next node has the same // data as the current nodeif(temp->next->data==curr->data){// Duplicate found, remove itNode*duplicate=temp->next;temp->next=temp->next->next;// Update the previous pointer of the// next node, if it existsif(temp->next!=nullptr)temp->next->prev=temp;// Free the memory of the duplicate nodedeleteduplicate;}else{// If the next node has different data from // the current node, move to the next nodetemp=temp->next;}}// Move to the next node in the listcurr=curr->next;}returnhead;}voidprintList(Node*head){Node*curr=head;while(curr!=nullptr){cout<<curr->data<<" ";curr=curr->next;}cout<<endl;}intmain(){// Create a doubly linked list:// 1 <-> 2 <-> 3 <-> 2 <-> 4Node*head=newNode(1);head->next=newNode(2);head->next->prev=head;head->next->next=newNode(3);head->next->next->prev=head->next;head->next->next->next=newNode(2);head->next->next->next->prev=head->next->next;head->next->next->next->next=newNode(4);head->next->next->next->next->prev=head->next->next->next;head=removeDuplicates(head);printList(head);return0;}
C
// C program to remove duplicates// from an unsorted doubly linked list#include<stdio.h>structNode{intdata;structNode*next;structNode*prev;};// Function to remove duplicates using nested loopsstructNode*removeDuplicates(structNode*head){structNode*curr=head;// Traverse each node in the listwhile(curr!=NULL){structNode*temp=curr;// Traverse the remaining nodes to// find and remove duplicateswhile(temp->next!=NULL){// Check if the next node has the same// data as the current nodeif(temp->next->data==curr->data){// Duplicate found, remove itstructNode*duplicate=temp->next;temp->next=temp->next->next;// Update the previous pointer of the next// node, if it existsif(temp->next!=NULL)temp->next->prev=temp;// Free the memory of the duplicate nodefree(duplicate);}else{// If the next node has different data from // the current node, move to the next nodetemp=temp->next;}}// Move to the next node in the listcurr=curr->next;}returnhead;}voidprintList(structNode*head){structNode*curr=head;while(curr!=NULL){printf("%d ",curr->data);curr=curr->next;}printf("\n");}structNode*createNode(intval){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->data=val;newNode->next=NULL;newNode->prev=NULL;returnnewNode;}intmain(){// Create a doubly linked list:// 1 <-> 2 <-> 3 <-> 2 <-> 4structNode*head=createNode(1);head->next=createNode(2);head->next->prev=head;head->next->next=createNode(3);head->next->next->prev=head->next;head->next->next->next=createNode(2);head->next->next->next->prev=head->next->next;head->next->next->next->next=createNode(4);head->next->next->next->next->prev=head->next->next->next;head=removeDuplicates(head);printList(head);return0;}
Java
// Java program to remove duplicates from// an unsorted doubly linked listclassNode{intdata;Nodenext;Nodeprev;Node(intval){data=val;next=null;prev=null;}}classGfG{staticNoderemoveDuplicates(Nodehead){Nodecurr=head;// Traverse each node in the listwhile(curr!=null){Nodetemp=curr;// Traverse the remaining nodes to// find and remove duplicateswhile(temp.next!=null){// Check if the next node has the same data// as the current nodeif(temp.next.data==curr.data){// Duplicate found, remove itNodeduplicate=temp.next;temp.next=temp.next.next;// Update the previous pointer of the// next node, if it existsif(temp.next!=null)temp.next.prev=temp;// Free the memory of the duplicate nodeduplicate=null;}else{// If the next node has different data from // the current node, move to the next nodetemp=temp.next;}}// Move to the next node in the listcurr=curr.next;}returnhead;}staticvoidprintList(Nodehead){Nodecurr=head;while(curr!=null){System.out.print(curr.data+" ");curr=curr.next;}System.out.println();}publicstaticvoidmain(String[]args){// Create a doubly linked list:// 1 <-> 2 <-> 3 <-> 2 <-> 4Nodehead=newNode(1);head.next=newNode(2);head.next.prev=head;head.next.next=newNode(3);head.next.next.prev=head.next;head.next.next.next=newNode(2);head.next.next.next.prev=head.next.next;head.next.next.next.next=newNode(4);head.next.next.next.next.prev=head.next.next.next;head=removeDuplicates(head);printList(head);}}
Python
# Python program to remove duplicates# from an unsorted doubly linked listclassNode:def__init__(self,val):self.data=valself.next=Noneself.prev=Nonedefprint_list(head):curr=headwhilecurrisnotNone:print(curr.data,end=" ")curr=curr.nextprint()defremove_duplicates(head):curr=head# Traverse each node in the listwhilecurrisnotNone:temp=curr# Traverse the remaining nodes to # find and remove duplicateswhiletemp.nextisnotNone:# Check if the next node has the same # data as the curr nodeiftemp.next.data==curr.data:# Duplicate found, remove itduplicate=temp.nexttemp.next=temp.next.next# Update the previous pointer of# the next node, if it existsiftemp.nextisnotNone:temp.next.prev=temp# Free the memory of the duplicate nodedelduplicateelse:# If the next node has different data from # the current node, move to the next nodetemp=temp.next# Move to the next node in the listcurr=curr.nextreturnheadif__name__=="__main__":# Create a doubly linked list:# 1 <-> 2 <-> 3 <-> 2 <-> 4head=Node(1)head.next=Node(2)head.next.prev=headhead.next.next=Node(3)head.next.next.prev=head.nexthead.next.next.next=Node(2)head.next.next.next.prev=head.next.nexthead.next.next.next.next=Node(4)head.next.next.next.next.prev=head.next.next.nexthead=remove_duplicates(head)print_list(head)
C#
// C# program to remove duplicates from an unsorted// doubly linked listusingSystem;classNode{publicintData;publicNodeNext;publicNodePrev;publicNode(intval){Data=val;Next=null;Prev=null;}}classGfG{staticvoidPrintList(Nodehead){Nodecurr=head;while(curr!=null){Console.Write(curr.Data+" ");curr=curr.Next;}Console.WriteLine();}staticNodeRemoveDuplicates(Nodehead){Nodecurr=head;// Traverse each node in the listwhile(curr!=null){Nodetemp=curr;// Traverse the remaining nodes to// find and remove duplicateswhile(temp.Next!=null){// Check if the next node has the same data// as the curr nodeif(temp.Next.Data==curr.Data){// Duplicate found, remove ittemp.Next=temp.Next.Next;// Update the previous pointer of the// next node, if it existsif(temp.Next!=null){temp.Next.Prev=temp;}}else{// If the next node has different data from // the current node, move to the next nodetemp=temp.Next;}}// Move to the next node in the listcurr=curr.Next;}returnhead;}staticvoidMain(){// Create a doubly linked list: // 1 <-> 2 <-> 3 <-> 2 <-> 4Nodehead=newNode(1);head.Next=newNode(2);head.Next.Prev=head;head.Next.Next=newNode(3);head.Next.Next.Prev=head.Next;head.Next.Next.Next=newNode(2);head.Next.Next.Next.Prev=head.Next.Next;head.Next.Next.Next.Next=newNode(4);head.Next.Next.Next.Next.Prev=head.Next.Next.Next;head=RemoveDuplicates(head);PrintList(head);}}
JavaScript
// Javascript program to remove duplicates from// an unsorted doubly linked listclassNode{constructor(val){this.data=val;this.next=null;this.prev=null;}}functionprintList(head){letcurr=head;while(curr!==null){console.log(curr.data+" ");curr=curr.next;}console.log();}functionremoveDuplicates(head){letcurr=head;// Traverse each node in the listwhile(curr!==null){lettemp=curr;// Traverse the remaining nodes to find and remove// duplicateswhile(temp.next!==null){// Check if the next node has the same data as// the curr nodeif(temp.next.data===curr.data){// Duplicate found, remove itletduplicate=temp.next;temp.next=temp.next.next;// Update the previous pointer of the next// node, if it existsif(temp.next!==null){temp.next.prev=temp;}// Free the memory of the duplicate nodedeleteduplicate;}else{// If the next node has different data from // the current node, move to the next nodetemp=temp.next;}}// Move to the next node in the listcurr=curr.next;}returnhead;}// Create a doubly linked list:// 1 <-> 2 <-> 3 <-> 2 <-> 4lethead=newNode(1);head.next=newNode(2);head.next.prev=head;head.next.next=newNode(3);head.next.next.prev=head.next;head.next.next.next=newNode(2);head.next.next.next.prev=head.next.next;head.next.next.next.next=newNode(4);head.next.next.next.next.prev=head.next.next.next;head=removeDuplicates(head);printList(head);
Output
1 2 3 4
Time Complexity: O(n^2),Two nested loops are used to find the duplicates. Auxiliary Space: O(1)
[Expected Approach] Using HashSet - O(n) Time and O(n) Space
The idea is to traverse the doubly linked list from head to end. For every newly encountered element
If the element is already present in the HashSet, remove it from the list.
If the elementis notin the HashSet, add it to the HashSet and move ahead in the list.
Step-by-step implementation:
Create a hash set for keeping track of data nodes.
Start traversing from the head of the list.
For each node check if node’s data is in the set:
If present, update pointers to remove the node and delete the node.
If not present thenadd the data into the set.
Below is the implementation of the above approach:
C++
// C++ implementation to remove duplicates from// an unsorted doubly linked list using hashing#include<iostream>#include<unordered_set>usingnamespacestd;classNode{public:intdata;Node*next;Node*prev;Node(intx){data=x;prev=nullptr;next=nullptr;}};Node*removeDuplicates(Node*head){unordered_set<int>hashSet;Node*curr=head;while(curr!=nullptr){// Check if the element is already in the hash tableif(hashSet.find(curr->data)!=hashSet.end()){// Element is present, remove it// Adjust previous node's next pointerif(curr->prev)curr->prev->next=curr->next;// Adjust next node's prev pointerif(curr->next)curr->next->prev=curr->prev;// Delete the curr nodeNode*temp=curr;curr=curr->next;deletetemp;}else{// Element is not present, add it to hash tablehashSet.insert(curr->data);curr=curr->next;}}returnhead;}voidprintList(Node*head){Node*curr=head;while(curr!=nullptr){cout<<curr->data<<" ";curr=curr->next;}cout<<endl;}intmain(){// Create a doubly linked list:// 1 <-> 2 <-> 3 <-> 2 <-> 4Node*head=newNode(1);head->next=newNode(2);head->next->prev=head;head->next->next=newNode(3);head->next->next->prev=head->next;head->next->next->next=newNode(2);head->next->next->next->prev=head->next->next;head->next->next->next->next=newNode(4);head->next->next->next->next->prev=head->next->next->next;head=removeDuplicates(head);printList(head);return0;}
Java
// Java implementation to remove duplicates from// an unsorted doubly linked list using hashingimportjava.util.HashSet;classNode{intdata;Nodenext;Nodeprev;Node(intx){data=x;next=null;prev=null;}}classGfG{staticNoderemoveDuplicates(Nodehead){HashSet<Integer>hashSet=newHashSet<>();Nodecurr=head;while(curr!=null){// Check if the element is already in the hash// tableif(hashSet.contains(curr.data)){// Element is present, remove it// Adjust previous node's next pointerif(curr.prev!=null)curr.prev.next=curr.next;// Adjust next node's prev pointerif(curr.next!=null)curr.next.prev=curr.prev;// Delete the curr nodeNodetemp=curr;curr=curr.next;temp=null;}else{// Element is not present, add it to hash// tablehashSet.add(curr.data);curr=curr.next;}}returnhead;}staticvoidprintList(Nodehead){Nodecurr=head;while(curr!=null){System.out.print(curr.data+" ");curr=curr.next;}System.out.println();}publicstaticvoidmain(String[]args){// Create a doubly linked list:// 1 <-> 2 <-> 3 <-> 2 <-> 4Nodehead=newNode(1);head.next=newNode(2);head.next.prev=head;head.next.next=newNode(3);head.next.next.prev=head.next;head.next.next.next=newNode(2);head.next.next.next.prev=head.next.next;head.next.next.next.next=newNode(4);head.next.next.next.next.prev=head.next.next.next;head=removeDuplicates(head);printList(head);}}
Python
# Python implementation to remove duplicates# from an unsorted doubly linked list using hashingclassNode:def__init__(self,x):self.data=xself.next=Noneself.prev=Nonedefremove_duplicates(head):hash_set=set()curr=headwhilecurrisnotNone:# Check if the element is already in the hash tableifcurr.datainhash_set:# Element is present, remove it# Adjust previous node's next pointerifcurr.prev:curr.prev.next=curr.next# Adjust next node's prev pointerifcurr.next:curr.next.prev=curr.prev# Delete the curr nodetemp=currcurr=curr.nextdeltempelse:# Element is not present, add it to hash tablehash_set.add(curr.data)curr=curr.nextreturnheaddefprint_list(head):curr=headwhilecurrisnotNone:print(curr.data,end=" ")curr=curr.nextprint()if__name__=="__main__":# Create a doubly linked list: # 1 <-> 2 <-> 3 <-> 2 <-> 4head=Node(1)head.next=Node(2)head.next.prev=headhead.next.next=Node(3)head.next.next.prev=head.nexthead.next.next.next=Node(2)head.next.next.next.prev=head.next.nexthead.next.next.next.next=Node(4)head.next.next.next.next.prev=head.next.next.nexthead=remove_duplicates(head)print_list(head)
C#
// C# implementation to remove duplicates from // an unsorted doubly linked list using hashingusingSystem;usingSystem.Collections.Generic;classNode{publicintData;publicNodeNext;publicNodePrev;publicNode(intx){Data=x;Next=null;Prev=null;}}classGfG{staticNodeRemoveDuplicates(Nodehead){HashSet<int>hashSet=newHashSet<int>();Nodecurr=head;while(curr!=null){// Check if the element is already in the hash tableif(hashSet.Contains(curr.Data)){// Element is present, remove it// Adjust previous node's next pointerif(curr.Prev!=null)curr.Prev.Next=curr.Next;// Adjust next node's prev pointerif(curr.Next!=null)curr.Next.Prev=curr.Prev;// Delete the current nodecurr=curr.Next;}else{// Element is not present, add it to hash tablehashSet.Add(curr.Data);curr=curr.Next;}}returnhead;}staticvoidPrintList(Nodehead){Nodecurr=head;while(curr!=null){Console.Write(curr.Data+" ");curr=curr.Next;}Console.WriteLine();}staticvoidMain(){// Create a doubly linked list: // 1 <-> 2 <-> 3 <-> 2 <-> 4Nodehead=newNode(1);head.Next=newNode(2);head.Next.Prev=head;head.Next.Next=newNode(3);head.Next.Next.Prev=head.Next;head.Next.Next.Next=newNode(2);head.Next.Next.Next.Prev=head.Next.Next;head.Next.Next.Next.Next=newNode(4);head.Next.Next.Next.Next.Prev=head.Next.Next.Next;head=RemoveDuplicates(head);PrintList(head);}}
JavaScript
// Javascript implementation to remove duplicates// from an unsorted doubly linked list using hashingclassNode{constructor(x){this.data=x;this.next=null;this.prev=null;}}functionremoveDuplicates(head){consthashSet=newSet();letcurr=head;while(curr!==null){// Check if the element is already in the hash tableif(hashSet.has(curr.data)){// Element is present, remove it// Adjust previous node's next pointerif(curr.prev)curr.prev.next=curr.next;// Adjust next node's prev pointerif(curr.next)curr.next.prev=curr.prev;// Delete the curr nodelettemp=curr;curr=curr.next;temp=null;}else{// Element is not present, add it to hash tablehashSet.add(curr.data);curr=curr.next;}}returnhead;}functionprintList(head){letcurr=head;while(curr!==null){console.log(curr.data+" ");curr=curr.next;}console.log();}// Create a doubly linked list:// 1 <-> 2 <-> 3 <-> 2 <-> 4lethead=newNode(1);head.next=newNode(2);head.next.prev=head;head.next.next=newNode(3);head.next.next.prev=head.next;head.next.next.next=newNode(2);head.next.next.next.prev=head.next.next;head.next.next.next.next=newNode(4);head.next.next.next.next.prev=head.next.next.next;head=removeDuplicates(head);printList(head);
Output
1 2 3 4
Time Complexity: O(n) , where n are the number of nodes in the doubly linked list. Auxiliary Space: O(n)