Design HashSet

Easy

Topics
ArrayHash TableDesign

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

returnsMyHashSet()add(1)add(2)contains(1)truecontains(3)falseadd(2)contains(2)trueremove(2)contains(2)false
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

  1. Keep an array of buckets; hash the key to a bucket index.
  2. add appends the key if not already present; remove deletes it.
  3. 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)
SensAI
Beta
Tap the mic to stop voice mode