Build a set with no built-in hash table: hash each key into one of 769 buckets, and keep a short list in each bucket for collisions.
▼The problem
LeetCode 705 (Easy). Design a hash set without any built-in hash table library: add(key), remove(key) and contains(key). Keys are 0..10^6, at most 10^4 calls. (Cousins in the series: ../design-hashmap (keys with values; its own look), ../contains-duplicate, ../two-sum, ../lru-cache, ../insert-delete-getrandom.)
Example (LeetCode's): add(1), add(2), contains(1) -> true, contains(3) -> false, add(2), contains(2) -> true, remove(2), contains(2) -> false, shown from outside in scene 2 and walked through on seven gates in scene 6 (buckets key % 7: 1, 2, 1, 3, 2, 2, 2, 2).
The solution
class MyHashSet:
def __init__(self):
self.size = 769
self.buckets = [[] for _ in range(self.size)]
def add(self, key):
b = self.buckets[key % self.size]
if key not in b:
b.append(key)
def remove(self, key):
b = self.buckets[key % self.size]
if key in b:
b.remove(key)
def contains(self, key):
return key in self.buckets[key % self.size]Transcript
Design HashSet. Build a set of numbers without any built-in hash table. Add puts a key in, remove takes it out, and contains asks whether it's there. Each key is stored only once.
Here's an example. Add one, add two. Contains one: true. Contains three: false. Add two again: it's already in, so nothing changes. Contains two: true. Remove two, and now contains two is false.
The simple way keeps one long list, and every call scans it from the start: order n per call. The other extreme keeps a slot for every possible key, a million and one of them. That's fast, but almost every slot sits empty.
The fix sits in between: buckets. A key's bucket is the key mod the number of buckets. With seven buckets, fifteen mod seven is one, so fifteen goes to bucket one. One also lands in bucket one: a collision. That's fine, because each bucket holds a short chain of keys, and the chain just grows. To find a key, work out its bucket and scan only that chain.
In code, make seven hundred sixty-nine empty buckets. It's a prime, which helps keys spread out. Every method first finds the key's bucket. Add appends the key only if the chain doesn't have it yet. Remove deletes it if it's there. Contains scans that one chain.
Let's walk the example on seven buckets. One goes to bucket one, two to bucket two. Contains one: it's there, true. Contains three: bucket three is empty, false. Add two again: already there, skip. Contains two: true. Remove two takes it off, so contains two is false.
The load factor is keys per bucket. Crowd eight keys onto two buckets and the chains get long. Spread them over enough buckets and each chain stays short, so every call is order one on average. Space is order of buckets plus keys.
Mod picks the bucket, scan one short chain, keep each key once. That's Design HashSet.