#705
Design HashSet
EasyArrayHash TableLinked ListDesignHash FunctionHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(1) on average |
| Space | O(1) | O(n) |
💡
Intuition
Time O(1) on averageSpace O(n)
The optimal solution uses a combination of an array and linked lists to handle collisions, which allows for efficient storage and retrieval of elements. This approach ensures that both the average time complexity for operations is reduced significantly.
⚙️
Algorithm
5 steps- 1Step 1: Create an array of buckets (lists) to store elements.
- 2Step 2: Use a hash function to determine the index for each key based on its value.
- 3Step 3: For 'add(key)', compute the index and add the key to the corresponding bucket if not present.
- 4Step 4: For 'contains(key)', compute the index and check if the key exists in the corresponding bucket.
- 5Step 5: For 'remove(key)', compute the index and remove the key from the corresponding bucket if it exists.
solution.py21 lines
1class MyHashSet:
2 def __init__(self):
3 self.size = 1000
4 self.buckets = [[] for _ in range(self.size)]
5
6 def _hash(self, key):
7 return key % self.size
8
9 def add(self, key):
10 bucket_index = self._hash(key)
11 if key not in self.buckets[bucket_index]:
12 self.buckets[bucket_index].append(key)
13
14 def contains(self, key):
15 bucket_index = self._hash(key)
16 return key in self.buckets[bucket_index]
17
18 def remove(self, key):
19 bucket_index = self._hash(key)
20 if key in self.buckets[bucket_index]:
21 self.buckets[bucket_index].remove(key)ℹ
Complexity note: The average time complexity for add, contains, and remove operations is O(1) due to the use of a hash function that distributes keys uniformly across the buckets. However, in the worst case (e.g., many collisions), it can degrade to O(n). The space complexity is O(n) because we store each key in the buckets.
- 1Using a hash function allows for efficient indexing of elements.
- 2Collision handling is crucial for maintaining performance.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.