Design a HashSet without using any built-in hash table libraries.
Implement
-
void add(key) Inserts the valuekey into the HashSet. -
bool contains(key) Returns whether the valuekey exists in the HashSet or not. -
void remove(key) Removes the valuekey in the HashSet. Ifkey does not exist in the HashSet, do nothing.
values = [[], [1], [2], [1], [3], [2], [2], [2], [2]]
Output: [null, null, null, true, false, null, true, null, false]
Explanation:
myHashSet.add(1); // set = [1]
myHashSet.add(2); // set = [1, 2]
myHashSet.contains(1); // return True
myHashSet.contains(3); // return False, (not found)
myHashSet.add(2); // set = [1, 2]
myHashSet.contains(2); // return True
myHashSet.remove(2); // set = [1]
myHashSet.contains(2); // return False, (already removed)
Constraints:
0 <= key <= 106 - At most 104 calls will be made to
add ,remove , andcontains .
Contents
Solution 1 - Using an array of LinkedLists
In this approach, we will use an array of
In order to find the index where to insert a given key, we will do a modular operation on the key value with array length, this will ensure that we will never got out of bounds of array.
Implementation steps:
-
Constructor: we will initialize array elements with empty
LinkedList , so that we don't need to donull
checks later. -
add(int key): we will get the index using
key % array.length , then check if thekey already in theLinkedList at that index or not, if it does not contain the key, then add it to the linked list. -
remove(int key): we will get the index using
key % array.length , then remove the entry with thekey from theLinkedList at that index. -
contains(int key): we will get the index using
key % array.length , then check if the element is present in theLinkedList at that index. If it present returntrue ,false otherwise.
Complexity Analysis:
Time complexity: All opeeration runs in O(1) time,
Space complexity: O(1) since we are storing elements into an array of linked lists.
Above implementations source code can be found at