Design HashSet (LeetCode 705): Solution and Explanation

Easy
Array
Hash Table
Linked List
Design
Hash Function

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

  1. Create 769 buckets, each an empty list.
  2. Compute the bucket of a key as key % 769.
  3. add(key): scan the key's bucket and append the key only if it is not already there.
  4. remove(key): scan the key's bucket and delete the key if it is found.
  5. 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]]
  1. MyHashSet() creates 769 empty buckets.
  2. add(1) hashes to bucket 1, which is empty, so 1 is appended. add(2) does the same in bucket 2.
  3. contains(1) checks bucket 1 and finds 1, so it returns true. contains(3) checks bucket 3, which is empty, so it returns false.
  4. add(2) finds 2 already in bucket 2 and changes nothing. contains(2) returns true.
  5. remove(2) unlinks 2 from bucket 2, and contains(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)]
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

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.

Space

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 add without checking first. The same key ends up in the chain twice, and one remove leaves a copy behind.
  • Removing by index instead of by value in Java (list.remove(key) on a List<Integer> removes the element at position key). Use Integer.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.