Remove duplicates from sorted list - leetcode solution
Remove duplicates from a sorted linked listWrite 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. Recommended: Please solve it on PRACTICE first, before moving on to the solution. Algorithm: Attention reader! Dont stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course. In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students. Implementation: C++
C
Java
Python3
C#
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. Recursive Approach : C++
C
Java
Python3
C#
Javascript
Output
Linked list before duplicate removal 11 11 11 13 13 20
Linked list after duplicate removal 11 13 20
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: C++14
Java
Python3
C#
Javascript
Output
List before removal of duplicates
11 11 11 13 13 20
List after removal of elements
11 13 20
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: C++
Java
Python3
C#
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)
Article Tags :
Linked List
Adobe Myntra Oracle Visa Practice Tags :
Oracle Visa Adobe Myntra Linked List
Read Full Article
|