This article is another part of a series on leet code problems solutions, and it provides a solution to the leet code problem number 83. This is a Leet code problem named Remove Duplicates from Sorted List. We will solve it using python and it is the best space and time-optimized solution.
Question of Remove Duplicates from Sorted List
Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
Create a function that removes any duplicate nodes from a list that has been sorted in non-decreasing order. There should only be one iteration of the list. For instance, removeDuplicates() should change the linked list from 11->11->11->21->43->43->50 to 11->21->43->50.
Example
Example 1
Input: head = [1,1,2]
Output: [1,2]
Example 2
Input: head = [1,1,2,3,3]
Output: [1,2,3]
Constraints
The number of nodes in the list is in the range [0, 300].
-100 <= Node.val <= 100
The list is guaranteed to be sorted in ascending order.
Approach to solve Remove Duplicates from Sorted List
From the head (or start) node, move down the list. Evaluate each node in relation to the node after it as you go. The next node should be deleted if its data is equal to that of the present node. We must save the node’s subsequent pointer before deleting it.
Algorithm
This method performs the following steps for a given input array:
Check base case i.e if head in None then return.
Assign head to temp to traverse in the list.
Repeat steps 4 to 6 till next of temp does not points to Null.
check if the current value is equal to the next value.
If Yes then unlink the next value by assigning the next of temp to the next of next of temp.
Otherwise, move the temp pointer to the next node
Python Code to Remove Duplicates from Sorted List
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def deleteDuplicates(self, head):
#Check base case
if head is None:
return head
#assign head to temp to traverse in list
temp = head
#run while loop till we reach end of loop
while temp.next :
#check if current value is equal to next value
if(temp.val == temp.next.val):
#if yes the unlink the next value
temp.next = temp.next.next
else:
#move temp pointer to next node
temp = temp.next
return head
Complexity Analysis
Time Complexity: O(n)
As we traverse to the whole linked list once
Space Complexity: O(1)
No extra space is required.
So here is the end of the post. If you find any issues or any questions then write a comment. Share with your friends.