Design a HashSet without using any built-in hash table libraries. Implement the MyHashSet
class:
void add(key):
Inserts the value key
into the HashSet.bool contains(key):
Returns whether the value key
exists in the HashSet or not.void remove(key):
Removes the value key
in the HashSet. If key
does not exist in the HashSet, do nothing.Given these constraints, we will use a simplistic yet effective approach to designing the HashSet.
We can simulate the behavior of a hash set using a list of lists (also known as buckets). The approach involves:
Key steps and design:
class MyHashSet:
def __init__(self):
"""
Initialize your data structure here.
"""
self.bucket_count = 1000
self.buckets = [[] for _ in range(self.bucket_count)]
def _hash(self, key: int) -> int:
"""
Hashing function to compute bucket index.
"""
return key % self.bucket_count
def add(self, key: int) -> None:
"""
Add a key into the HashSet.
"""
bucket_index = self._hash(key)
if key not in self.buckets[bucket_index]:
self.buckets[bucket_index].append(key)
def remove(self, key: int) -> None:
"""
Remove a key from the HashSet.
"""
bucket_index = self._hash(key)
if key in self.buckets[bucket_index]:
self.buckets[bucket_index].remove(key)
def contains(self, key: int) -> bool:
"""
Returns true if this set contains the specified element
"""
bucket_index = self._hash(key)
return key in self.buckets[bucket_index]
# Initialize a new HashSet
hashSet = MyHashSet()
# Add elements
hashSet.add(1)
hashSet.add(2)
# Check for elements
print(hashSet.contains(1)) # Returns True
print(hashSet.contains(3)) # Returns False
# Remove an element
hashSet.remove(2)
# Check again
print(hashSet.contains(2)) # Returns False
This solution provides a simple and effective way of implementing a HashSet using a fixed bucket array and basic list operations, focusing on constant time complexity for average-case scenarios.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?