Design a HashSet without using any built-in hash table libraries.
Implement MyHashSet
class:
void add(int key)
: Inserts the value key into the HashSet.bool contains(int key)
: Returns whether the value key exists in the HashSet or not.void remove(int key)
: Removes the value key in the HashSet. If key does not exist in the HashSet, do nothing.key
values that we need to handle?
[0, 10^6)
.We’ll use a combination of a hash table with chaining to handle collisions and an array to store the values. Here is the strategy:
#include <vector>
#include <list>
class MyHashSet {
private:
static const int BUCKET_SIZE = 769; // A prime number bucket size
std::vector<std::list<int>> buckets;
int hash(int key) {
return key % BUCKET_SIZE;
}
public:
MyHashSet() {
buckets.resize(BUCKET_SIZE);
}
void add(int key) {
int bucket_idx = hash(key);
auto &bucket = buckets[bucket_idx];
for (int el : bucket) {
if (el == key) return; // Key already exists
}
bucket.push_back(key);
}
bool contains(int key) {
int bucket_idx = hash(key);
auto &bucket = buckets[bucket_idx];
for (int el : bucket) {
if (el == key) return true;
}
return false;
}
void remove(int key) {
int bucket_idx = hash(key);
auto &bucket = buckets[bucket_idx];
bucket.remove(key); // Removes the first occurrence of key
}
};
/**
* Your MyHashSet object will be instantiated and called as such:
* MyHashSet* obj = new MyHashSet();
* obj->add(key);
* bool param_2 = obj->contains(key);
* obj->remove(key);
*/
This approach effectively balances the need for simplicity and efficiency, ensuring that operations remain performant across a wide range of expected inputs.
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?