VOOZH about

URL: https://www.geeksforgeeks.org/dsa/remove-duplicates-unsorted-doubly-linked-list/

⇱ Remove duplicates from an unsorted doubly linked list - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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

👁 Remove-duplicates-from-a-sorted-linked-list
Removal of duplicate node 2 from Doubly Linked List

Input: 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:


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 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:


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)

Comment
Article Tags: