# Javascript Program For Removing Duplicates From A Sorted Linked List

Last Updated : 15 Jun, 2022

Write a function that takes a list sorted in non-decreasing order and deletes any duplicate nodes from the list. The list should only be traversed once.
For example if the linked list is 11->11->11->21->43->43->60 then removeDuplicates() should convert the list to 11->21->43->60.

Algorithm:
Traverse the list from the head (or start) node. While traversing, compare each node with its next node. If the data of the next node is the same as the current node then delete the next node. Before we delete a node, we need to store the next pointer of the node

Implementation:
Functions other than removeDuplicates() are just to create a linked list and test removeDuplicates().

## Javascript

 ``

Output:

```Linked list before duplicate removal  11 11 11 13 13 20
Linked list after duplicate removal  11 13 20```

Time Complexity: O(n) where n is the number of nodes in the given linked list.

Auxiliary Space: O(1)

Recursive Approach :

## Javascript

 ``

Output

```Linked list before duplicate removal  11 11 11 13 13 20
Linked list after duplicate removal  11 13 20```

Time Complexity: O(n), where n is the number of nodes in the given linked list.

Auxiliary Space: O(n), due to recursive stack where n is the number of nodes in the given linked list.

Another Approach: Create a pointer that will point towards the first occurrence of every element and another pointer temp which will iterate to every element and when the value of the previous pointer is not equal to the temp pointer, we will set the pointer of the previous pointer to the first occurrence of another node.

Below is the implementation of the above approach:

## Javascript

 ``

Output

```List before removal of duplicates
11 11 11 13 13 20
List after removal of elements
11 13 20 ```

Time Complexity: O(n) where n is the number of nodes in the given linked list.
Auxiliary Space: O(1), no extra space is required, so it is a constant.

Another Approach: Using Maps

The idea is to push all the values in a map and printing its keys.

Below is the implementation of the above approach:

## Javascript

 ``

Output

```Linked list before duplicate removal 11 11 11 13 13 20
Linked list after duplicate removal 11 13 20 ```

Time Complexity: O(Number of Nodes)

Space Complexity: O(Number of Nodes)

Please refer complete article on Remove duplicates from a sorted linked list for more details!

Previous
Next