




Sponsored
Sponsored
The direct address table approach is simple and efficient for this problem since the maximum key size is limited to 106. We can use a boolean array of size 106+1 where each index represents a key. The value stored at a given index indicates whether the key is present in the HashSet. This allows for O(1) time complexity for the 'add', 'remove', and 'contains' operations.
Time Complexity: O(1) for all operations (add, remove, contains).
Space Complexity: O(MAX), which is O(10^6).
1#include <vector>
2
3class MyHashSet {
4private:
5    std::vector<bool> container;
6public:
7    MyHashSet() : container(1000001, false) {}
8
9    void add(int key) {
10        container[key] = true;
11    }
12
13    void remove(int key) {
14        container[key] = false;
15    }
16
17    bool contains(int key) {
18        return container[key];
19    }
20};
21In C++, we use a vector initialized with false values up to the maximum key size. The add, remove, and contains methods operate directly on this vector's indices.
This approach simulates a hash set using a hash function to assign keys to buckets, dealing with potential collisions using chaining. We create an array of lists, where each list contains keys that hash to the same index. This way, operations require traversing these short lists upon collisions.
Time Complexity: O(1) average, O(n) worst-case for add, remove, and contains due to collision chains.
Space Complexity: O(n), where n is the number of keys actually added.
1
Java uses an array of 'Bucket' objects, where each bucket maintains a linked list of keys hashing to its index. Methods to insert, delete, and verify key presence operate on these linked lists. The hash function uses modulus to assign keys to buckets.