Design HashSet — Bit Array or Chaining Approach
Advertisement
Problem 193 · Design HashSet
Difficulty: Medium · Pattern: Custom Hash Table
Implement add, remove, contains without built-in hash set.
Solutions
# Python — bit array (values 0..10^6)
class MyHashSet:
def __init__(self): self.data = [False] * 1000001
def add(self, key): self.data[key] = True
def remove(self, key): self.data[key] = False
def contains(self, key): return self.data[key]
// Java — chaining
class MyHashSet {
private static final int SIZE = 1009;
private LinkedList<Integer>[] set;
public MyHashSet() { set = new LinkedList[SIZE]; }
private int hash(int key) { return key % SIZE; }
public void add(int key) {
int h = hash(key);
if (set[h] == null) set[h] = new LinkedList<>();
if (!set[h].contains(key)) set[h].add(key);
}
public void remove(int key) {
int h = hash(key);
if (set[h] != null) set[h].remove((Integer)key);
}
public boolean contains(int key) {
int h = hash(key);
return set[h] != null && set[h].contains(key);
}
}
// C++
class MyHashSet {
static const int SIZE = 1009;
vector<list<int>> buckets;
public:
MyHashSet() : buckets(SIZE) {}
void add(int key) {
auto& b = buckets[key%SIZE];
if (find(b.begin(),b.end(),key)==b.end()) b.push_back(key);
}
void remove(int key) { buckets[key%SIZE].remove(key); }
bool contains(int key) {
auto& b = buckets[key%SIZE];
return find(b.begin(),b.end(),key) != b.end();
}
};
Complexity
- Time: O(1) amortized
- Space: O(n)
Advertisement