Design HashSet
Easy
Topics
Design a HashSet without using any built-in hash set libraries. Implement MyHashSet with add(key), contains(key) (returns whether the key is present), and remove(key).
Example 1
A set of integers built without the language’s own: add, remove, and ask whether a key is present. A key is held at most once, so adding one that is already there changes nothing, and removing one that was never added is not an error.
Calls run top to bottom; the arrow shows what each one returns.
Input: operations = ["MyHashSet","add","add","contains","contains","add","contains","remove","contains"], values = [[],[1],[2],[1],[3],[2],[2],[2],[2]] Output: [null,null,null,true,false,null,true,null,false]
Constraints
- 0 <= key <= 10^6
- At most 10^4 calls to add, remove, and contains.
Editorial — intuition, approach, complexity and pitfalls
Intuition
A hash set stores membership only. Bucket each key by a hash and keep the keys that collide in the same bucket.
Approach
- Keep an array of buckets; hash the key to a bucket index.
- add appends the key if not already present; remove deletes it.
- contains scans the bucket for the key.
Dry Run
MyHashSet() -- 1009 buckets, index = key % 1009
add 1 -> null bucket 1: [1]
add 2 -> null bucket 1: [1] bucket 2: [2]
contains 1 -> true scan bucket 1
contains 3 -> false bucket 3 is empty
add 2 -> null bucket 2: [2] already present, nothing appended
contains 2 -> true
remove 2 -> null bucket 2: []
contains 2 -> false
answer null|null|null|true|false|null|true|null|false
The second "add 2" is the row that matters. The bucket still holds a single 2,
because add checks membership before appending. That check is not about wasted
space -- remove only deletes the FIRST matching entry, so a duplicate would
survive it. Drop the guard, run add 1, add 2, add 2, then remove 2, and bucket 2
still reads [2] with contains(2) returning true when it should be false.
A set stores bare keys where a map stores pairs, and that is the only structural
difference between the two. Everything else -- bucket array, modulo hash, linear
scan within a bucket -- is identical.
Note that remove on an absent key is a no-op rather than an error, which is what
makes the sequence "remove 2, remove 2, add 1, add 1" return nothing but nulls.Complexity
- Time — O(1) average: each operation touches one short bucket.
- Space — O(n): stored keys plus the bucket array.
Common Pitfalls
- add must not insert duplicates.
Full Solution — all languages
class MyHashSet:
def __init__(self):
self.n = 1009
self.buckets = [[] for _ in range(self.n)]
def add(self, key):
b = self.buckets[key % self.n]
if key not in b:
b.append(key)
def contains(self, key):
return key in self.buckets[key % self.n]
def remove(self, key):
b = self.buckets[key % self.n]
if key in b:
b.remove(key)import java.util.*;
class MyHashSet {
static final int N = 1009;
List<Integer>[] buckets;
public MyHashSet() {
buckets = new List[N];
for (int i = 0; i < N; i++) buckets[i] = new ArrayList<>();
}
public void add(int key) {
List<Integer> b = buckets[key % N];
if (!b.contains(key)) b.add(key);
}
public boolean contains(int key) {
return buckets[key % N].contains(key);
}
public void remove(int key) {
buckets[key % N].remove(Integer.valueOf(key));
}
}#include <bits/stdc++.h>
using namespace std;
class MyHashSet {
static const int N = 1009;
vector<vector<int>> buckets;
public: MyHashSet() : buckets(N) {
}
void add(int key) {
auto& b = buckets[key % N];
for (int x : b) if (x == key) return;
b.push_back(key);
}
bool contains(int key) {
for (int x : buckets[key % N]) if (x == key) return true;
return false;
}
void remove(int key) {
auto& b = buckets[key % N];
for (size_t i = 0; i < b.size(); i++) if (b[i] == key) {
b.erase(b.begin() + i);
return;
}
}
};class MyHashSet {
constructor() {
this.n = 1009;
this.buckets = Array.from({ length: this.n }, () => []);
}
add(key) {
const b = this.buckets[key % this.n];
if (b.indexOf(key) === -1) b.push(key);
}
contains(key) {
return this.buckets[key % this.n].indexOf(key) !== -1;
}
remove(key) {
const b = this.buckets[key % this.n];
const i = b.indexOf(key);
if (i !== -1) b.splice(i, 1);
}
}