Design HashSet (LeetCode 705): Solution and Explanation
Build an integer set with add, remove and contains without any built-in hash table. Keys range from 0 to 10^6 and there are at most 10^4 calls, so the goal is near O(1) per call with memory that tracks the keys actually stored.
Intuition
The simplest answer is a boolean array with one slot per possible key. It works here, but it spends a million slots on at most ten thousand keys. A hash set trades that for a small fixed array of buckets and a rule that maps any key to one of them.
The rule is key % 769. Every key lands in exactly one bucket, so to answer any question about a key you only ever look inside that one bucket.
Different keys can map to the same bucket, for example 5, 774 and 1543 all give 5. That is a collision, and the standard fix is separate chaining: each bucket keeps a short list, and you scan that list for the key.
Picking a prime bucket count matters when keys follow a pattern. Keys that are all multiples of 100 would pile into a few buckets with 1000 buckets, but they spread out over 769.
Approach: Fixed buckets with separate chaining
- Create 769 buckets, each an empty list.
- Compute the bucket of a key as
key % 769. add(key): scan the key's bucket and append the key only if it is not already there.remove(key): scan the key's bucket and delete the key if it is found.contains(key): scan the key's bucket and report whether the key is in it.
Step-by-step example
commands = ["MyHashSet","add","add","contains","contains","add","contains","remove","contains"], values = [[],[1],[2],[1],[3],[2],[2],[2],[2]]
MyHashSet()creates 769 empty buckets.add(1)hashes to bucket 1, which is empty, so 1 is appended.add(2)does the same in bucket 2.contains(1)checks bucket 1 and finds 1, so it returns true.contains(3)checks bucket 3, which is empty, so it returns false.add(2)finds 2 already in bucket 2 and changes nothing.contains(2)returns true.remove(2)unlinks 2 from bucket 2, andcontains(2)now returns false. Output: [null,null,null,true,false,null,true,null,false].
Code: Python, Java, C++
1class MyHashSet:
2 def __init__(self):
3 self.size = 769
4 self.buckets = [[] for _ in range(self.size)]
5
6 def _hash(self, key: int) -> int:
7 return key % self.size
8
9 def add(self, key: int) -> None:
10 bucket = self.buckets[self._hash(key)]
11 if key not in bucket:
12 bucket.append(key)
13
14 def remove(self, key: int) -> None:
15 bucket = self.buckets[self._hash(key)]
16 if key in bucket:
17 bucket.remove(key)
18
19 def contains(self, key: int) -> bool:
20 return key in self.buckets[self._hash(key)]1class MyHashSet {
2 private static final int SIZE = 769;
3 private List<List<Integer>> buckets;
4
5 public MyHashSet() {
6 buckets = new ArrayList<>();
7 for (int i = 0; i < SIZE; i++) {
8 buckets.add(new LinkedList<>());
9 }
10 }
11
12 private int hashKey(int key) {
13 return key % SIZE;
14 }
15
16 public void add(int key) {
17 List<Integer> bucket = buckets.get(hashKey(key));
18 if (!bucket.contains(key)) {
19 bucket.add(key);
20 }
21 }
22
23 public void remove(int key) {
24 List<Integer> bucket = buckets.get(hashKey(key));
25 if (bucket.contains(key)) {
26 bucket.remove(Integer.valueOf(key));
27 }
28 }
29
30 public boolean contains(int key) {
31 return buckets.get(hashKey(key)).contains(key);
32 }
33}1class MyHashSet {
2 static const int SIZE = 769;
3 vector<list<int>> buckets;
4
5 int hashKey(int key) {
6 return key % SIZE;
7 }
8
9public:
10 MyHashSet() {
11 buckets.resize(SIZE);
12 }
13
14 void add(int key) {
15 list<int>& bucket = buckets[hashKey(key)];
16 if (find(bucket.begin(), bucket.end(), key) == bucket.end()) {
17 bucket.push_back(key);
18 }
19 }
20
21 void remove(int key) {
22 list<int>& bucket = buckets[hashKey(key)];
23 if (find(bucket.begin(), bucket.end(), key) != bucket.end()) {
24 bucket.remove(key);
25 }
26 }
27
28 bool contains(int key) {
29 list<int>& bucket = buckets[hashKey(key)];
30 return find(bucket.begin(), bucket.end(), key) != bucket.end();
31 }
32};Time and space complexity
O(n / b) average per call
Each call scans one bucket. With n stored keys spread over b = 769 buckets, a chain holds about n / b keys, which is a small constant for this problem's limits.
O(b + n)
The bucket array has b entries, and each stored key appears in exactly one chain.
Other approaches
Direct-address boolean array (time O(1), space O(max key))
Allocate 10^6 + 1 booleans and flip the slot for each key. Every call is a single array access, but the memory is fixed at a million entries no matter how few keys are stored.
Buckets with balanced trees (time O(log(n / b)) per call, space O(b + n))
Replace each chain with a binary search tree so a crowded bucket is searched in O(log k) instead of O(k). Java's HashMap switches to this when a chain grows long. It is more code and only pays off with adversarial keys.
Common mistakes
- Appending in
addwithout checking first. The same key ends up in the chain twice, and oneremoveleaves a copy behind. - Removing by index instead of by value in Java (
list.remove(key)on aList<Integer>removes the element at positionkey). UseInteger.valueOf(key). - Using a bucket count like 1000 or a power of two. Patterned keys then collide far more than they need to.
- Searching every bucket in
contains. Only the key's own bucket can hold it.
Frequently asked questions
Why 769 buckets?
It is a prime a little under 1000. A prime modulus does not share factors with common key patterns, so keys like multiples of 10 or 100 still spread across many buckets.
What happens when two keys hash to the same bucket?
Both are stored in that bucket's chain. Lookups hash to the bucket and then compare keys one by one along the chain, so a collision costs a few extra comparisons but never gives a wrong answer.
Should the set resize as it grows?
Real hash sets double their bucket count when the load factor passes a threshold, so chains stay short no matter how many keys arrive. With at most 10^4 calls a fixed 769 buckets keeps chains short enough, so resizing is optional here.