Design HashSet

Easyhash-tabledesign
Category: System Design
Companies that ask this question:
AmazonGoogle

Approach

Design HashSet

Approach

Use array of buckets with simple modulo hash function.

Algorithm

  1. Hash function: key % size
  2. Add: Hash key, add to bucket if not present
  3. Remove: Hash key, remove from bucket
  4. Contains: Hash key, check bucket

Complexity

  • Time: O(n/k) average where k is bucket count
  • Space: O(k + m) where m is number of unique keys

Key Insights

  • Chaining handles collisions
  • Simple modulo hash distributes keys
  • Each bucket stores colliding keys

Solution

java
1class MyHashSet {
2    private List<Integer>[] buckets;
3    private int size = 1000;
4    
5    public MyHashSet() {
6        buckets = new List[size];
7        for (int i = 0; i < size; i++) {
8            buckets[i] = new ArrayList<>();
9        }
10    }
11    
12    private int hash(int key) {
13        return key % size;
14    }
15    
16    public void add(int key) {
17        int idx = hash(key);
18        if (!buckets[idx].contains(key)) {
19            buckets[idx].add(key);
20        }
21    }
22    
23    public void remove(int key) {
24        int idx = hash(key);
25        buckets[idx].remove(Integer.valueOf(key));
26    }
27    
28    public boolean contains(int key) {
29        int idx = hash(key);
30        return buckets[idx].contains(key);
31    }
32}
Loading visualizer...