Design a HashMap without using any built-in hash table libraries.
Implement the MyHashMap class:
MyHashMap() initializes the object with an empty map.void put(int key, int value) inserts a (key, value) pair into the HashMap. If the key already exists in the map, update the corresponding value.int get(int key) returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key.void remove(key) removes the key and its corresponding value if the map contains the mapping for the key. Input:
["MyHashMap", "put", "put", "get", "get", "put", "get", "remove", "get"][[], [1, 1], [2, 2], [1], [3], [2, 1], [2], [2], [2]]
Output
[null, null, null, 1, -1, null, 1, null, -1]
Explanation:
put, get, and remove.The simplest way to implement a hashmap is to use an array where each index holds a linked list of key-value pairs. This method handles collisions by chaining entries together in the form of a linked list. When adding a new entry, we first compute its hash code which gives us the index to put the key-value pair into, and we toggle through the linked list to either update the value or insert a new node.
O(N/B), where N is the number of all possible keys and B is the number of buckets.O(M + N), where M is the given element size and N is the bucket size which is 10000 here.By using a secondary hashing technique, we can better address the issue of collision. This involves using an open addressing scheme where slots are utilized in alternative locations if collisions occur. Double hashing uses two hash functions to compute bucket locations.
O(1) for put, get, and delete operations.O(U) where U is the universe of keys. In this approach, space can be large if the range of key values is vast.Instead of using linked lists for collisions, we can use a Binary Search Tree (BST). This gives faster operations in a scenario with worst-case time complexity, and makes the performance more stable by reducing the potential of long chains experienced with a basic linked list structure. This approach provides O(log N) operations where N is the number of keys stored in the bucket.
O(log N) where N is the number of elements in a bucket.O(N) where N is the total number of elements.