Problem
Design a HashSet without using the language's built-in set. Support add, remove and contains for non-negative integers.
Original: LeetCode 705: Design HashSet.
Examples
Example 1
`MyHashSet: add(1), add(2), contains(1), contains(3), add(2), contains(2), remove(2), contains(2)``[null, null, true, false, null, true, null, false]`Constraints
0 <= key <= 10^6- At most
10^4calls will be made toadd,remove, andcontains.
Hints
Hint 1
Operations should be average constant time. Values can be repeated in add; the set should stay unique.
Hint 2
A hash table with separate chaining, or a boolean array if the official value range is small enough.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. A single list of keys is correct but linear per operation.
Optimal. An array of lists, with a prime or a reasonably large bucket count, and a simple modulo hash. You can also use a boolean array of size 10^6+1, because the official constraints allow it, but the bucket design is the one to explain.
Alternative. Open addressing with linear probing is also a valid hash table, but deletion is more delicate.
Complexity
- Time
- O(1)
Average O(1) per operation when keys hash evenly, and O(n) in a worst-case bucket. Space is O(n + B), where B is the number of buckets.
- Space
- O(n + B)
Code
class MyHashSet:
def __init__(self) -> None:
self.buckets: list[list[int]] = [[] for _ in range(769)]
def _bucket(self, key: int) -> list[int]:
return self.buckets[key % len(self.buckets)]
def add(self, key: int) -> None:
b = self._bucket(key)
if key not in b:
b.append(key)
def remove(self, key: int) -> None:
b = self._bucket(key)
if key in b:
b.remove(key)
def contains(self, key: int) -> bool:
return key in self._bucket(key)
if __name__ == "__main__":
s = MyHashSet()
s.add(1)
s.add(2)
assert s.contains(1) is True and s.contains(3) is False
s.add(2)
assert s.contains(2) is True
s.remove(2)
assert s.contains(2) is False
print("ok")import java.util.ArrayList;
import java.util.List;
public class DesignHashSet {
private final List<Integer>[] buckets;
@SuppressWarnings("unchecked")
DesignHashSet() {
buckets = new ArrayList[769];
for (int i = 0; i < buckets.length; i++) buckets[i] = new ArrayList<>();
}
void add(int key) {
var b = buckets[key % buckets.length];
if (!b.contains(key)) b.add(key);
}
void remove(int key) {
buckets[key % buckets.length].remove(Integer.valueOf(key));
}
boolean contains(int key) {
return buckets[key % buckets.length].contains(key);
}
public static void main(String[] args) {
var s = new DesignHashSet();
s.add(1);
s.add(2);
if (!s.contains(1) || s.contains(3)) throw new AssertionError();
s.add(2);
if (!s.contains(2)) throw new AssertionError();
s.remove(2);
if (s.contains(2)) throw new AssertionError();
System.out.println("ok");
}
}Edge cases
- Official sample: add 1 and 2, contains(1) is true, contains(3) is false, add 2 again, contains(2) is true, remove 2, then contains(2) is false.
- remove on a missing key is a no-op. In Java, remove(Integer.valueOf(key)) so you delete the value, not an index.
Follow-ups
- Design HashMap adds a value beside each key, with the same bucket structure.
- A production set would resize when the load factor grows.
Interview script
"I use separate chaining: an array of lists, and the bucket is key modulo the table size. add, remove and contains only walk that one bucket. If they want a simpler version, a boolean array also works under the official value range."
Source: LeetCode 705: Design HashSet Source: Java SE 17 API: ArrayList.remove)
Sources (2)
- LeetCode 705: Design HashSetleetcode.com
- Java SE 17 API: ArrayList.removedocs.oracle.com