Remove Duplicates From Linked List - Cracking the Coding Interview, Leetcode
Shirley
Posted on August 20, 2020
This problem appears in both Cracking the Cracking Interview and Leetcode. The problem is this: given a linked list, delete duplicates such that each number appears only once.
For example:
input: 1 -> 1 -> 2
output: 1 -> 2
Here's a hint. Use a hashset to store your unique numbers in, and if the number exists already in the hashset, set the pointer of the previous node equal to the next node of current node.
class Node:
self.data = data
self.next = None
class Solution:
def removeDuplicates(self, head:Node) -> Node:
hashSet = set()
node = head
prev = None
while node:
if node.data not in hashSet:
hashSet.add(node.data)
prev = node
else:
prev.next = node.next
node = node.next
return head
đź’– đź’Ş đź™… đźš©
Shirley
Posted on August 20, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.