SDE & MLE Prep

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]