Design HashSet
Problem
Design a HashSet without using any built-in hash table libraries, supporting add, remove, and contains operations for integer keys.
- 0 ≤ key ≤ 10⁶
- At most 10⁴ calls will be made to add, remove, and contains.
Example
add(1), add(2), contains(1), contains(3), add(2), contains(2), remove(2), contains(2)[null, null, true, false, null, true, null, false]Initially, the set is empty. After add(1) and add(2), contains(1) returns true because 1 was added. contains(3) returns false because 3 was never added. add(2) again does not change the set. contains(2) returns true. remove(2) deletes 2 from the set. Finally, contains(2) returns false because 2 was removed.
Approach
Straightforward Solution
A naive approach is to store keys in a list and perform linear scans for add, remove, and contains operations, resulting in O(n) time per operation, which is inefficient for large inputs.
Core Observation
A HashSet stores unique keys and supports fast insertion, deletion, and membership queries. The fundamental principle is to distribute keys uniformly across buckets using a hash function to achieve average O(1) time complexity for these operations.
Path to Optimal
The key recognition signals are 'store unique keys', 'support add/remove/contains', and 'no built-in hash table'. These indicate implementing a hash map with separate chaining using buckets. The modulo operation on the key provides a simple hash function to assign keys to buckets. Each bucket is a list storing keys with the same hash. This approach reduces average operation time to O(1) assuming uniform distribution and small bucket sizes.
Optimal Approach
Implement the HashSet with a fixed number of buckets (a prime number to reduce collisions). Use the modulo of the key to determine the bucket index. For add, check if the key is already in the bucket; if not, append it. For remove, check if the key is in the bucket and remove it. For contains, check membership in the bucket. This design achieves average O(1) time per operation with O(n) space proportional to the number of keys stored.
Time
O(1) average per operation
Each operation computes the bucket index in O(1) time and performs a membership check or update in a small list. Assuming uniform distribution, bucket sizes remain small, making these operations average O(1).
Space
O(n)
Space grows linearly with the number of unique keys stored, as each key is stored exactly once in one of the buckets.
Pattern Spotlight
Hash Maps (Separate Chaining with Buckets)
Use a fixed-size array of buckets indexed by a hash function (modulo) to distribute keys evenly, and store colliding keys in lists within each bucket to maintain efficient average-case operations.
Solution
| 1 | class MyHashSet: |
| 2 | |
| 3 | def __init__(self): |
| 4 | self.bucket_count = 1009 |
| 5 | self.buckets = [[] for _ in range(self.bucket_count)] |
| 6 | |
| 7 | def _get_bucket(self, key: int) -> list: |
| 8 | bucket_index = key % self.bucket_count |
| 9 | return self.buckets[bucket_index] |
| 10 | |
| 11 | def add(self, key: int) -> None: |
| 12 | bucket = self._get_bucket(key) |
| 13 | |
| 14 | if key not in bucket: |
| 15 | bucket.append(key) |
| 16 | |
| 17 | def remove(self, key: int) -> None: |
| 18 | bucket = self._get_bucket(key) |
| 19 | |
| 20 | if key in bucket: |
| 21 | bucket.remove(key) |
| 22 | |
| 23 | def contains(self, key: int) -> bool: |
| 24 | bucket = self._get_bucket(key) |
| 25 | return key in bucket |
Step-by-Step Solution
Initialize Buckets Array with Fixed Prime Size
| 4 | self.bucket_count = 1009 |
| 5 | self.buckets = [[] for _ in range(self.bucket_count)] |
Objective
To create a fixed-size array of empty buckets to store keys, enabling efficient hashing and collision handling.
Key Insight
Choosing a prime number for the bucket count helps distribute keys uniformly when using modulo hashing. Initializing each bucket as an empty list prepares the data structure for separate chaining, where each bucket handles collisions by storing multiple keys.
Interview Quick-Check
Core Logic
Buckets are initialized as a list of empty lists, each representing a chain to handle collisions.
Common Pitfalls & Bugs
Choosing a non-prime bucket count can lead to poor key distribution and increased collisions.
Compute Bucket Index Using Modulo Hash Function
| 7 | def _get_bucket(self, key: int) -> list: |
| 8 | bucket_index = key % self.bucket_count |
| 9 | return self.buckets[bucket_index] |
Objective
To map any given key to its corresponding bucket index using a simple and fast hash function.
Key Insight
The modulo operation with the bucket count provides a deterministic and uniform way to assign keys to buckets. This ensures that keys are distributed across buckets, minimizing collisions and maintaining efficient lookup times.
Interview Quick-Check
Core Logic
The bucket index is computed as key modulo bucket_count, ensuring keys map to valid bucket indices.
Common Pitfalls & Bugs
Forgetting to use modulo can cause index errors or poor distribution.
Add Key to Bucket if Not Present
| 12 | bucket = self._get_bucket(key) |
| 14 | if key not in bucket: |
| 15 | bucket.append(key) |
Objective
To insert a key into its bucket only if it is not already present, maintaining set uniqueness.
Key Insight
Before adding, checking for the key's presence prevents duplicates, preserving the HashSet property. Appending to the bucket list is efficient since bucket sizes are expected to be small due to uniform hashing.
Interview Quick-Check
Core Logic
Add operation first checks if the key is absent in the bucket to avoid duplicates, then appends it.
Common Pitfalls & Bugs
Failing to check for existing keys can lead to duplicates, violating set semantics.
Remove Key from Bucket if Present
| 18 | bucket = self._get_bucket(key) |
| 20 | if key in bucket: |
| 21 | bucket.remove(key) |
Objective
To delete a key from its bucket if it exists, enabling efficient removal from the HashSet.
Key Insight
Checking for the key's presence before removal prevents errors. Removing from a list is O(n) in the worst case, but bucket sizes are small on average, keeping removal efficient.
Interview Quick-Check
Core Logic
Remove operation checks for key presence and removes it from the bucket list if found.
Common Pitfalls & Bugs
Attempting to remove a non-existent key without checking can cause runtime errors.
Check Key Membership in Bucket
| 24 | bucket = self._get_bucket(key) |
| 25 | return key in bucket |
Objective
To determine if a key exists in the HashSet by checking its bucket.
Key Insight
Membership check uses the same hash function to locate the bucket and then performs a membership test in the bucket list. This operation is efficient due to small bucket sizes and direct indexing.
Interview Quick-Check
Core Logic
Contains operation computes the bucket and returns whether the key is in that bucket.
Common Pitfalls & Bugs
Using a different hash function or forgetting to check the correct bucket leads to incorrect membership results.
Line Analysis
This solution has 3 Critical lines interviewers watch for.
bucket_index = key % self.bucket_count
Calculate the bucket index by taking key modulo bucket_count.
Modulo operation ensures the bucket index is within valid bounds and distributes keys evenly across buckets.
if key not in bucket:
Check if the key is not already in the bucket before adding.
Preventing duplicates preserves the set property that each key appears only once.
return key in bucket
Return whether the key is present in the bucket.
This membership test determines if the key exists in the HashSet, fulfilling the contains operation.
self.bucket_count = 1009
Set the number of buckets to a prime number (1009) for hashing.
Using a prime number for bucket count reduces collisions by distributing keys more uniformly when using modulo hashing.
self.buckets = [[] for _ in range(self.bucket_count)]
Initialize the buckets as a list of empty lists for separate chaining.
Each bucket is a list that will hold keys hashing to the same index, enabling collision handling via chaining.
bucket.append(key)
Append the key to the bucket list if absent.
Adding the key to the bucket stores it in the HashSet, enabling future membership queries.
if key in bucket:
Check if the key exists in the bucket before removal.
Ensures safe removal and prevents errors from attempting to remove a non-existent key.
bucket.remove(key)
Remove the key from the bucket list.
Deleting the key updates the HashSet to reflect the removal operation.
return self.buckets[bucket_index]
Return the bucket list corresponding to the computed index.
This provides direct access to the bucket where the key should be stored or searched.
def add(self, key: int) -> None:
Retrieve the bucket for the key to add.
Locating the correct bucket is necessary to maintain the HashSet's structure and ensure efficient operations.
def remove(self, key: int) -> None:
Retrieve the bucket for the key to remove.
Locating the correct bucket is essential to efficiently find and remove the key if it exists.
def contains(self, key: int) -> bool:
Retrieve the bucket for the key to check membership.
Locating the correct bucket is necessary to efficiently determine if the key is present.
def _get_bucket(self, key: int) -> list:
Define a helper method to compute the bucket for a given key.
Encapsulating the hash function logic improves code clarity and reuse, ensuring consistent bucket indexing.
bucket = self._get_bucket(key)
Assign the bucket to a local variable for manipulation.
Using a local variable improves readability and avoids repeated calls to the helper method.
bucket = self._get_bucket(key)
Assign the bucket to a local variable for manipulation.
Using a local variable simplifies subsequent operations on the bucket.
bucket = self._get_bucket(key)
Assign the bucket to a local variable for membership check.
Using a local variable improves code clarity and avoids redundant calls.
Test Your Understanding
Why does using a modulo operation with a prime number of buckets help maintain efficient average-case performance?
Using a prime number for the bucket count reduces the likelihood of key collisions by distributing keys more uniformly across buckets, which keeps bucket sizes small and operations efficient.
Related Problems
Hash Maps pattern
Don't just read it. Drill it.
Reconstruct Design HashSet from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.
Unlock the Design HashSet drill