Remove duplicates from an unsorted doubly linked list
Last Updated :
28 Aug, 2024
Given an unsorted doubly linked list containing n nodes, the task is to remove duplicate nodes while preserving the original order.
Examples:
Input: Doubly Linked List = 1 <-> 2 <-> 3 <-> 2 <-> 4
Output: Doubly Linked List = 1 <-> 2 <-> 3 <-> 4
Removal of duplicate node 2 from Doubly Linked ListInput: Doubly Linked List = 8 <-> 4 <-> 4 <-> 6 <-> 4 <-> 8 <-> 4 <-> 10 <-> 12 <-> 12
Output: Doubly Linked List = 8 <-> 4 <-> 6 <-> 10 <-> 12
[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>
using namespace std;
class Node {
public:
int data;
Node* next;
Node* prev;
Node(int val) {
data = val;
next = nullptr;
prev = nullptr;
}
};
// Function to remove duplicates using nested loops
Node* removeDuplicates(Node* head) {
Node* curr = head;
// Traverse each node in the list
while (curr != nullptr) {
Node* temp = curr;
// Traverse the remaining nodes to find and
// remove duplicates
while (temp->next != nullptr) {
// Check if the next node has the same
// data as the current node
if (temp->next->data == curr->data) {
// Duplicate found, remove it
Node* duplicate = temp->next;
temp->next = temp->next->next;
// Update the previous pointer of the
// next node, if it exists
if (temp->next != nullptr)
temp->next->prev = temp;
// Free the memory of the duplicate node
delete duplicate;
}
else {
// If the next node has different data from
// the current node, move to the next node
temp = temp->next;
}
}
// Move to the next node in the list
curr = curr->next;
}
return head;
}
void printList(Node* head) {
Node* curr = head;
while (curr != nullptr) {
cout << curr->data << " ";
curr = curr->next;
}
cout << endl;
}
int main() {
// Create a doubly linked list:
// 1 <-> 2 <-> 3 <-> 2 <-> 4
Node* head = new Node(1);
head->next = new Node(2);
head->next->prev = head;
head->next->next = new Node(3);
head->next->next->prev = head->next;
head->next->next->next = new Node(2);
head->next->next->next->prev = head->next->next;
head->next->next->next->next = new Node(4);
head->next->next->next->next->prev = head->next->next->next;
head = removeDuplicates(head);
printList(head);
return 0;
}
C
// C program to remove duplicates
// from an unsorted doubly linked list
#include <stdio.h>
struct Node {
int data;
struct Node *next;
struct Node *prev;
};
// Function to remove duplicates using nested loops
struct Node *removeDuplicates(struct Node *head) {
struct Node *curr = head;
// Traverse each node in the list
while (curr != NULL) {
struct Node *temp = curr;
// Traverse the remaining nodes to
// find and remove duplicates
while (temp->next != NULL) {
// Check if the next node has the same
// data as the current node
if (temp->next->data == curr->data) {
// Duplicate found, remove it
struct Node *duplicate = temp->next;
temp->next = temp->next->next;
// Update the previous pointer of the next
// node, if it exists
if (temp->next != NULL)
temp->next->prev = temp;
// Free the memory of the duplicate node
free(duplicate);
}
else {
// If the next node has different data from
// the current node, move to the next node
temp = temp->next;
}
}
// Move to the next node in the list
curr = curr->next;
}
return head;
}
void printList(struct Node *head) {
struct Node *curr = head;
while (curr != NULL) {
printf("%d ", curr->data);
curr = curr->next;
}
printf("\n");
}
struct Node *createNode(int val) {
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->data = val;
newNode->next = NULL;
newNode->prev = NULL;
return newNode;
}
int main() {
// Create a doubly linked list:
// 1 <-> 2 <-> 3 <-> 2 <-> 4
struct Node *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);
return 0;
}
Java
// Java program to remove duplicates from
// an unsorted doubly linked list
class Node {
int data;
Node next;
Node prev;
Node(int val) {
data = val;
next = null;
prev = null;
}
}
class GfG {
static Node removeDuplicates(Node head) {
Node curr = head;
// Traverse each node in the list
while (curr != null) {
Node temp = curr;
// Traverse the remaining nodes to
// find and remove duplicates
while (temp.next != null) {
// Check if the next node has the same data
// as the current node
if (temp.next.data == curr.data) {
// Duplicate found, remove it
Node duplicate = temp.next;
temp.next = temp.next.next;
// Update the previous pointer of the
// next node, if it exists
if (temp.next != null)
temp.next.prev = temp;
// Free the memory of the duplicate node
duplicate = null;
}
else {
// If the next node has different data from
// the current node, move to the next node
temp = temp.next;
}
}
// Move to the next node in the list
curr = curr.next;
}
return head;
}
static void printList(Node head) {
Node curr = head;
while (curr != null) {
System.out.print(curr.data + " ");
curr = curr.next;
}
System.out.println();
}
public static void main(String[] args) {
// Create a doubly linked list:
// 1 <-> 2 <-> 3 <-> 2 <-> 4
Node head = new Node(1);
head.next = new Node(2);
head.next.prev = head;
head.next.next = new Node(3);
head.next.next.prev = head.next;
head.next.next.next = new Node(2);
head.next.next.next.prev = head.next.next;
head.next.next.next.next = new Node(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 list
class Node:
def __init__(self, val):
self.data = val
self.next = None
self.prev = None
def print_list(head):
curr = head
while curr is not None:
print(curr.data, end=" ")
curr = curr.next
print()
def remove_duplicates(head):
curr = head
# Traverse each node in the list
while curr is not None:
temp = curr
# Traverse the remaining nodes to
# find and remove duplicates
while temp.next is not None:
# Check if the next node has the same
# data as the curr node
if temp.next.data == curr.data:
# Duplicate found, remove it
duplicate = temp.next
temp.next = temp.next.next
# Update the previous pointer of
# the next node, if it exists
if temp.next is not None:
temp.next.prev = temp
# Free the memory of the duplicate node
del duplicate
else:
# If the next node has different data from
# the current node, move to the next node
temp = temp.next
# Move to the next node in the list
curr = curr.next
return head
if __name__ == "__main__":
# Create a doubly linked list:
# 1 <-> 2 <-> 3 <-> 2 <-> 4
head = Node(1)
head.next = Node(2)
head.next.prev = head
head.next.next = Node(3)
head.next.next.prev = head.next
head.next.next.next = Node(2)
head.next.next.next.prev = head.next.next
head.next.next.next.next = Node(4)
head.next.next.next.next.prev = head.next.next.next
head = remove_duplicates(head)
print_list(head)
C#
// C# program to remove duplicates from an unsorted
// doubly linked list
using System;
class Node {
public int Data;
public Node Next;
public Node Prev;
public Node(int val) {
Data = val;
Next = null;
Prev = null;
}
}
class GfG {
static void PrintList(Node head) {
Node curr = head;
while (curr != null) {
Console.Write(curr.Data + " ");
curr = curr.Next;
}
Console.WriteLine();
}
static Node RemoveDuplicates(Node head) {
Node curr = head;
// Traverse each node in the list
while (curr != null) {
Node temp = curr;
// Traverse the remaining nodes to
// find and remove duplicates
while (temp.Next != null) {
// Check if the next node has the same data
// as the curr node
if (temp.Next.Data == curr.Data) {
// Duplicate found, remove it
temp.Next = temp.Next.Next;
// Update the previous pointer of the
// next node, if it exists
if (temp.Next != null) {
temp.Next.Prev = temp;
}
}
else {
// If the next node has different data from
// the current node, move to the next node
temp = temp.Next;
}
}
// Move to the next node in the list
curr = curr.Next;
}
return head;
}
static void Main() {
// Create a doubly linked list:
// 1 <-> 2 <-> 3 <-> 2 <-> 4
Node head = new Node(1);
head.Next = new Node(2);
head.Next.Prev = head;
head.Next.Next = new Node(3);
head.Next.Next.Prev = head.Next;
head.Next.Next.Next = new Node(2);
head.Next.Next.Next.Prev = head.Next.Next;
head.Next.Next.Next.Next = new Node(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 list
class Node {
constructor(val) {
this.data = val;
this.next = null;
this.prev = null;
}
}
function printList(head) {
let curr = head;
while (curr !== null) {
console.log(curr.data + " ");
curr = curr.next;
}
console.log();
}
function removeDuplicates(head) {
let curr = head;
// Traverse each node in the list
while (curr !== null) {
let temp = curr;
// Traverse the remaining nodes to find and remove
// duplicates
while (temp.next !== null) {
// Check if the next node has the same data as
// the curr node
if (temp.next.data === curr.data) {
// Duplicate found, remove it
let duplicate = temp.next;
temp.next = temp.next.next;
// Update the previous pointer of the next
// node, if it exists
if (temp.next !== null) {
temp.next.prev = temp;
}
// Free the memory of the duplicate node
delete duplicate;
}
else {
// If the next node has different data from
// the current node, move to the next node
temp = temp.next;
}
}
// Move to the next node in the list
curr = curr.next;
}
return head;
}
// Create a doubly linked list:
// 1 <-> 2 <-> 3 <-> 2 <-> 4
let head = new Node(1);
head.next = new Node(2);
head.next.prev = head;
head.next.next = new Node(3);
head.next.next.prev = head.next;
head.next.next.next = new Node(2);
head.next.next.next.prev = head.next.next;
head.next.next.next.next = new Node(4);
head.next.next.next.next.prev = head.next.next.next;
head = removeDuplicates(head);
printList(head);
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 element is not in 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 then add 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>
using namespace std;
class Node {
public:
int data;
Node *next;
Node *prev;
Node(int x) {
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 table
if (hashSet.find(curr->data) != hashSet.end()) {
// Element is present, remove it
// Adjust previous node's next pointer
if (curr->prev)
curr->prev->next = curr->next;
// Adjust next node's prev pointer
if (curr->next)
curr->next->prev = curr->prev;
// Delete the curr node
Node *temp = curr;
curr = curr->next;
delete temp;
}
else {
// Element is not present, add it to hash table
hashSet.insert(curr->data);
curr = curr->next;
}
}
return head;
}
void printList(Node *head) {
Node *curr = head;
while (curr != nullptr) {
cout << curr->data << " ";
curr = curr->next;
}
cout << endl;
}
int main() {
// Create a doubly linked list:
// 1 <-> 2 <-> 3 <-> 2 <-> 4
Node *head = new Node(1);
head->next = new Node(2);
head->next->prev = head;
head->next->next = new Node(3);
head->next->next->prev = head->next;
head->next->next->next = new Node(2);
head->next->next->next->prev = head->next->next;
head->next->next->next->next = new Node(4);
head->next->next->next->next->prev = head->next->next->next;
head = removeDuplicates(head);
printList(head);
return 0;
}
Java
// Java implementation to remove duplicates from
// an unsorted doubly linked list using hashing
import java.util.HashSet;
class Node {
int data;
Node next;
Node prev;
Node(int x) {
data = x;
next = null;
prev = null;
}
}
class GfG {
static Node removeDuplicates(Node head) {
HashSet<Integer> hashSet = new HashSet<>();
Node curr = head;
while (curr != null) {
// Check if the element is already in the hash
// table
if (hashSet.contains(curr.data)) {
// Element is present, remove it
// Adjust previous node's next pointer
if (curr.prev != null)
curr.prev.next = curr.next;
// Adjust next node's prev pointer
if (curr.next != null)
curr.next.prev = curr.prev;
// Delete the curr node
Node temp = curr;
curr = curr.next;
temp = null;
}
else {
// Element is not present, add it to hash
// table
hashSet.add(curr.data);
curr = curr.next;
}
}
return head;
}
static void printList(Node head) {
Node curr = head;
while (curr != null) {
System.out.print(curr.data + " ");
curr = curr.next;
}
System.out.println();
}
public static void main(String[] args) {
// Create a doubly linked list:
// 1 <-> 2 <-> 3 <-> 2 <-> 4
Node head = new Node(1);
head.next = new Node(2);
head.next.prev = head;
head.next.next = new Node(3);
head.next.next.prev = head.next;
head.next.next.next = new Node(2);
head.next.next.next.prev = head.next.next;
head.next.next.next.next = new Node(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 hashing
class Node:
def __init__(self, x):
self.data = x
self.next = None
self.prev = None
def remove_duplicates(head):
hash_set = set()
curr = head
while curr is not None:
# Check if the element is already in the hash table
if curr.data in hash_set:
# Element is present, remove it
# Adjust previous node's next pointer
if curr.prev:
curr.prev.next = curr.next
# Adjust next node's prev pointer
if curr.next:
curr.next.prev = curr.prev
# Delete the curr node
temp = curr
curr = curr.next
del temp
else:
# Element is not present, add it to hash table
hash_set.add(curr.data)
curr = curr.next
return head
def print_list(head):
curr = head
while curr is not None:
print(curr.data, end=" ")
curr = curr.next
print()
if __name__ == "__main__":
# Create a doubly linked list:
# 1 <-> 2 <-> 3 <-> 2 <-> 4
head = Node(1)
head.next = Node(2)
head.next.prev = head
head.next.next = Node(3)
head.next.next.prev = head.next
head.next.next.next = Node(2)
head.next.next.next.prev = head.next.next
head.next.next.next.next = Node(4)
head.next.next.next.next.prev = head.next.next.next
head = remove_duplicates(head)
print_list(head)
C#
// C# implementation to remove duplicates from
// an unsorted doubly linked list using hashing
using System;
using System.Collections.Generic;
class Node {
public int Data;
public Node Next;
public Node Prev;
public Node(int x) {
Data = x;
Next = null;
Prev = null;
}
}
class GfG {
static Node RemoveDuplicates(Node head) {
HashSet<int> hashSet = new HashSet<int>();
Node curr = head;
while (curr != null) {
// Check if the element is already in the hash table
if (hashSet.Contains(curr.Data)) {
// Element is present, remove it
// Adjust previous node's next pointer
if (curr.Prev != null)
curr.Prev.Next = curr.Next;
// Adjust next node's prev pointer
if (curr.Next != null)
curr.Next.Prev = curr.Prev;
// Delete the current node
curr = curr.Next;
}
else {
// Element is not present, add it to hash table
hashSet.Add(curr.Data);
curr = curr.Next;
}
}
return head;
}
static void PrintList(Node head) {
Node curr = head;
while (curr != null) {
Console.Write(curr.Data + " ");
curr = curr.Next;
}
Console.WriteLine();
}
static void Main() {
// Create a doubly linked list:
// 1 <-> 2 <-> 3 <-> 2 <-> 4
Node head = new Node(1);
head.Next = new Node(2);
head.Next.Prev = head;
head.Next.Next = new Node(3);
head.Next.Next.Prev = head.Next;
head.Next.Next.Next = new Node(2);
head.Next.Next.Next.Prev = head.Next.Next;
head.Next.Next.Next.Next = new Node(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 hashing
class Node {
constructor(x) {
this.data = x;
this.next = null;
this.prev = null;
}
}
function removeDuplicates(head) {
const hashSet = new Set();
let curr = head;
while (curr !== null) {
// Check if the element is already in the hash table
if (hashSet.has(curr.data)) {
// Element is present, remove it
// Adjust previous node's next pointer
if (curr.prev)
curr.prev.next = curr.next;
// Adjust next node's prev pointer
if (curr.next)
curr.next.prev = curr.prev;
// Delete the curr node
let temp = curr;
curr = curr.next;
temp = null;
}
else {
// Element is not present, add it to hash table
hashSet.add(curr.data);
curr = curr.next;
}
}
return head;
}
function printList(head) {
let curr = head;
while (curr !== null) {
console.log(curr.data + " ");
curr = curr.next;
}
console.log();
}
// Create a doubly linked list:
// 1 <-> 2 <-> 3 <-> 2 <-> 4
let head = new Node(1);
head.next = new Node(2);
head.next.prev = head;
head.next.next = new Node(3);
head.next.next.prev = head.next;
head.next.next.next = new Node(2);
head.next.next.next.prev = head.next.next;
head.next.next.next.next = new Node(4);
head.next.next.next.next.prev = head.next.next.next;
head = removeDuplicates(head);
printList(head);
Time Complexity: O(n) , where n are the number of nodes in the doubly linked list.
Auxiliary Space: O(n)
Similar Reads
Basics & Prerequisites
Data Structures
Getting Started with Array Data StructureArray is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
14 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem