GeeksforGeeks App
Open App
Browser
Continue

# Javascript Program For Removing Duplicates From An Unsorted Linked List

Write a removeDuplicates() function that takes a list and deletes any duplicate nodes from the list. The list is not sorted.
For example if the linked list is 12->11->12->21->41->43->21 then removeDuplicates() should convert the list to 12->11->21->41->43.

METHOD 1 (Using two loops):
This is the simple way where two loops are used. 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.
Thanks to Gaurav Saxena for his help in writing this code.

## Javascript

 ``

Output:

```Linked list before removing duplicates:
10 12 11 11 12 11 10
10 12 11```

Time Complexity: O(n^2)

Space Complexity: O(1), since it does not use any additional data structure to remove duplicates.

METHOD 2 (Use Sorting):
In general, Merge Sort is the best-suited sorting algorithm for sorting linked lists efficiently.
1) Sort the elements using Merge Sort. We will soon be writing a post about sorting a linked list. O(nLogn)
2) Remove duplicates in linear time using the algorithm for removing duplicates in sorted Linked List. O(n)
Please note that this method doesn’t preserve the original order of elements.
Time Complexity: O(nLogn)

METHOD 3 (Use Hashing):
We traverse the link list from head to end. For every newly encountered element, we check whether it is in the hash table: if yes, we remove it; otherwise we put it in the hash table.

## Javascript

 ``

Output:

```Linked list before removing duplicates:
10 12 11 11 12 11 10