Design a HashSet without using any built-in hash table libraries.

Implement MyHashSet class:

  • MyHashSet() Initializes the MyHashSet object.
  • void add(key) Inserts the value key into the HashSet.
  • bool contains(key) Returns whether the value key exists in the HashSet or not.
  • void remove(key) Removes the value key in the HashSet. If key does 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
HashSet Design OverviewOperationsadd, remove, containsHash TableBuckets + Hash FunctionResultsnull, true, falseadd(1): Insert key 1contains(1): Check if 1 existsremove(1): Delete key 1hash(1) = 1 % 1000 = 1Store in bucket[1]O(1) average lookupadd → nullcontains → trueremove → null
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
Asked in
Google 35 Facebook 28 Amazon 25 Microsoft 22
125.0K Views
Medium Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen