Remove Duplicates from Sorted List
Question
Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1: Input: 1->1->2 Output: 1->2
Example 1: Input: 1->1->2->3->3 Output: 1->2->3
Approach 1: Dummy List
This problem is similar to Q21, because they both require traverse a
linked list. In fact, the key point is to set out=mid=head
.
out
is used in the iterations and mid
is used
as an output.
1 | # Definition for singly-linked list. |
Complexity Analysis
- Runtime: 48 ms, faster than 87.51% of Python3 online submissions forRemove Duplicates from Sorted List.
- Memory Usage: 13.3 MB, less than 22.63% of Python3 online submissions for Remove Duplicates from Sorted List.
Approach 2: Straight-Forward
This is a simple problem that merely tests your ability to manipulate
list node pointers. Because the input list is sorted, we can determine
if a node is a duplicate by comparing its value to the node
after it in the list. If it is a duplicate, we change the
next
pointer of the current node so that it skips the next
node and points directly to the one after the next node.
1 | class Solution: |
Complexity Analysis
Time complexity : O(n). Because each node in the list is checked exactly once to determine if it is a duplicate or not, the total run time is O(n), where n is the number of nodes in the list.
Space complexity : O(1). No additional space is used.
Runtime: 48 ms, faster than 87.51% of Python3 online submissions forRemove Duplicates from Sorted List.
Memory Usage: 13.3 MB, less than 22.63% of Python3 online submissions for Remove Duplicates from Sorted List.