Create a hashset

Not sure why I did this, but its a very simple problem. The problem is to create a hashset without using any built in libraries. I guess we can use arrays or lists. This problem can be found in leetcode at this link .

Following is pretty self explanatory solution that beats 97% of the solution in Leetcode.

class MyHashSet: def get_hash(self,key): return key%self.hashsize def __init__(self): self.hashsize = 1000 self.arr = [[] for i in range(self.hashsize)] def add(self, key: int) -> None: hashval = self.get_hash(key) if key in self.arr[hashval]: pass else: self.arr[hashval].append(key) def remove(self, key: int) -> None: hashval = self.get_hash(key) if key in self.arr[hashval]: self.arr[hashval].remove(key) def contains(self, key: int) -> bool: hashval = self.get_hash(key) if key in self.arr[hashval]: return True else: return False # Your MyHashSet object will be instantiated and called as such: # obj = MyHashSet() # obj.add(key) # obj.remove(key) # param_3 = obj.contains(key)

Another solution: same solution

The code looks a bit better if we use set() instead of list().

class MyHashSet: def get_hash(self,key): return key%self.hashsize def __init__(self): self.hashsize = 1000 self.arr = [set() for i in range(self.hashsize)] def add(self, key: int) -> None: hashval = self.get_hash(key) self.arr[hashval].add(key) def remove(self, key: int) -> None: hashval = self.get_hash(key) self.arr[hashval].discard(key) def contains(self, key: int) -> bool: hashval = self.get_hash(key) if key in self.arr[hashval]: return True else: return False # Your MyHashSet object will be instantiated and called as such: # obj = MyHashSet() # obj.add(key) # obj.remove(key) # param_3 = obj.contains(key)