705. Design HashSet
Problem
Design MyHashSet without built-in hash tables: add(key), remove(key) and contains(key).
Example: add 1, add 2 → contains(1) = true, contains(3) = false; add 2, remove 2 → contains(2) = false
Constraints: keys ≤ 10⁶; up to 10⁴ calls.
Separate chaining: an array of buckets (a prime count spreads keys evenly), each a small list; hash = key % buckets. Operations scan one bucket. Follow-ups: resize (rehash into 2× buckets) when the load factor grows; open addressing with tombstones as the alternative.
Complexity: O(1) average per operation.
class MyHashSet:
def __init__(self):
self.size = 1009
self.buckets = [[] for _ in range(self.size)]
def add(self, key: int) -> None:
b = self.buckets[key % self.size]
if key not in b:
b.append(key)
def remove(self, key: int) -> None:
b = self.buckets[key % self.size]
if key in b:
b.remove(key)
def contains(self, key: int) -> bool:
return key in self.buckets[key % self.size]
hs = MyHashSet()
hs.add(1); hs.add(2)
assert hs.contains(1) and not hs.contains(3)
hs.add(2)
assert hs.contains(2)
hs.remove(2)
assert not hs.contains(2)
hs.add(0); hs.add(1009); hs.add(2018) # same bucket
hs.remove(1009)
assert hs.contains(0) and not hs.contains(1009) and hs.contains(2018)
class MyHashSet {
private static final int SIZE = 1009;
private final List<List<Integer>> buckets = new ArrayList<>();
public MyHashSet() { for (int i = 0; i < SIZE; i++) buckets.add(new LinkedList<>()); }
public void add(int key) { if (!contains(key)) buckets.get(key % SIZE).add(key); }
public void remove(int key) { buckets.get(key % SIZE).remove(Integer.valueOf(key)); }
public boolean contains(int key) { return buckets.get(key % SIZE).contains(key); }
}
type MyHashSet struct {
buckets [][]int // separate chaining
}
const size = 1009 // a prime number of buckets
func Constructor() MyHashSet {
return MyHashSet{buckets: make([][]int, size)}
}
func (this *MyHashSet) Add(key int) {
if !this.Contains(key) {
this.buckets[key%size] = append(this.buckets[key%size], key)
}
}
func (this *MyHashSet) Remove(key int) {
b := this.buckets[key%size]
for i, k := range b {
if k == key {
this.buckets[key%size] = append(b[:i], b[i+1:]...)
return
}
}
}
func (this *MyHashSet) Contains(key int) bool {
for _, k := range this.buckets[key%size] {
if k == key {
return true
}
}
return false
}