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