Design HashSet - Problem
Design a HashSet without using any built-in hash table libraries.
Implement MyHashSet class:
MyHashSet()Initializes the MyHashSet object.void add(key)Inserts the valuekeyinto the HashSet.bool contains(key)Returns whether the valuekeyexists in the HashSet or not.void remove(key)Removes the valuekeyin the HashSet. Ifkeydoes not exist in the HashSet, do nothing.
Your implementation should handle typical hash set operations efficiently.
Input & Output
Example 1 — Basic Operations
$
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]
💡 Note:
Initialize empty set, add 1 and 2, check if 1 exists (true), check if 3 exists (false), add 2 again (no change), check if 2 exists (true), remove 2, check if 2 exists (false)
Example 2 — Remove Non-existent
$
Input:
operations = ["MyHashSet", "add", "remove", "contains"], values = [[], [5], [10], [5]]
›
Output:
[null, null, null, true]
💡 Note:
Add 5 to set, try to remove 10 (doesn't exist, no change), check if 5 exists (true)
Example 3 — Duplicate Adds
$
Input:
operations = ["MyHashSet", "add", "add", "contains"], values = [[], [7], [7], [7]]
›
Output:
[null, null, null, true]
💡 Note:
Add 7, add 7 again (no change since sets don't allow duplicates), check if 7 exists (true)
Constraints
- 0 ≤ key ≤ 106
- At most 104 calls will be made to add, remove, and contains
Visualization
Tap to expand
Understanding the Visualization
1
Input Operations
Sequence of add, remove, and contains operations
2
Hash Function
Map keys to buckets using modulo operation
3
Output Results
Return null for add/remove, boolean for contains
Key Takeaway
🎯 Key Insight: Hash functions distribute keys evenly across buckets for O(1) average operations
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code