Remove Duplicated from Sorted List II
Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.
Approach1: Two pass - Dictionary
My first thought upon reading this problem is to use a dictionary to solve it. We would first do a first pass through which the dictionary would store the frequency of each value of the Linked List. Having stored the frequencies, we execute a second pass so we can now delete each values for which their count in the dictionary is greater than 1 hence a duplicate.
Time: O(n) Space: O(n)
Approach2: One Pass (optimal)
Although the above code works perfectly, we know that considering that the Linked List is sorted, we should be able to avoid utilizing any additional additional data structures that are ramping up our space complexity. After profound reflection (not really, got the hint :) ), we should be able to get O(1) space by applying this fundamental concept.
Iterate through the Linked List with a curr pointer pointer followed by a prev pointer. When the curr pointer encounters an element that is equal to it's current value. Curr pointer runs until it's next element does not equal to it's current value. Once that occurs, prev pointer's -> next then prints at curr's -> next thereby deleting all elements that were duplicates. As often with Linked List's, we return dummy->next.
Last updated
Was this helpful?