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.Example 1:
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 MyHashMap myHashMap = new MyHashMap(); myHashMap.put(1, 1); // The map is now [[1,1]] myHashMap.put(2, 2); // The map is now [[1,1], [2,2]] myHashMap.get(1); // return 1, The map is now [[1,1], [2,2]] myHashMap.get(3); // return -1 (i.e., not found), The map is now [[1,1], [2,2]] myHashMap.put(2, 1); // The map is now [[1,1], [2,1]] (i.e., update the existing value) myHashMap.get(2); // return 1, The map is now [[1,1], [2,1]] myHashMap.remove(2); // remove the mapping for 2, The map is now [[1,1]] myHashMap.get(2); // return -1 (i.e., not found), The map is now [[1,1]]
Constraints:
0 <= key, value <= 106104 calls will be made to put, get, and remove.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have a giant blank notebook where you need to remember pairs of things, like a person's name and their phone number. The simplest and most straightforward way to handle this is to just write every single pair down on a long list of paper one after the other.
Here's how the algorithm would work step-by-step:
class MyHashMap:
def __init__(self):
self.entry_storage_list = []
def put(self, key: int, value: int) -> None:
# We iterate to update existing keys instead of duplicating, ensuring uniqueness per key
for entry_index, stored_pair in enumerate(self.entry_storage_list):
if stored_pair[0] == key:
self.entry_storage_list[entry_index] = (key, value)
return
self.entry_storage_list.append((key, value))
def get(self, key: int) -> int:
# Linear scan is required to check every element sequentially since keys are unordered
for stored_pair in self.entry_storage_list:
if stored_pair[0] == key:
return stored_pair[1]
return -1
def remove(self, key: int) -> None:
# We iterate backward or filter to safely remove the target key without index shifting bugs
for entry_index, stored_pair in enumerate(self.entry_storage_list):
if stored_pair[0] == key:
del self.entry_storage_list[entry_index]
returnInstead of keeping everything in one long, unorganized list, the optimal approach divides items into several labeled filing cabinets based on their unique identification numbers. This way, when you need to find, add, or remove something, you only have to look through a tiny fraction of the total items rather than searching through everything.
Here's how the algorithm would work step-by-step:
class MyHashMap:
def __init__(self):
self.bucket_count = 2069
self.bucket_array = [[] for _ in range(self.bucket_count)]
def _hash_function(self, target_key):
return target_key % self.bucket_count
def put(self, target_key: int, target_value: int) -> None:
bucket_index = self._hash_function(target_key)
target_bucket = self.bucket_array[bucket_index]
# We iterate through the bucket to check if the key already exists to prevent duplicates.
for index, pair in enumerate(target_bucket):
if pair[0] == target_key:
target_bucket[index] = (target_key, target_value)
return
target_bucket.append((target_key, target_value))
def get(self, target_key: int) -> int:
bucket_index = self._hash_function(target_key)
target_bucket = self.bucket_array[bucket_index]
# We search specifically within the assigned bucket to ensure fast retrieval times.
for pair in target_bucket:
if pair[0] == target_key:
return pair[1]
return -1
def remove(self, target_key: int) -> None:
bucket_index = self._hash_function(target_key)
target_bucket = self.bucket_array[bucket_index]
# We check every stored pair in the bucket to isolate and safely delete the target key.
for index, pair in enumerate(target_bucket):
if pair[0] == target_key:
target_bucket.pop(index)
return| Case | How to Handle |
|---|---|
| Key already exists during an insert operation | The update operation overwrites the existing value associated with that key instead of creating a duplicate entry. |
| Key does not exist during a get or remove operation | The lookup returns negative one or gracefully skips deletion if the key is absent from the bucket. |
| Negative keys or zero as a key | The hash function applies an absolute value or modulo operation properly to map negative integers to valid bucket indices. |
| Maximum possible integer values for keys | The hash function uses safe arithmetic or bitwise operations to prevent integer overflow during index calculation. |
| High collision rate due to poorly distributed keys | Each bucket uses a linked list or secondary data structure to handle multiple entries mapping to the same index. |
| Removing the only element in a bucket | The bucket head pointer is updated directly to null or the next node to maintain correct list integrity. |
| Removing the head node of a bucket's linked list | A dummy or sentinel node at the start of each bucket simplifies pointer manipulation during deletion. |
| Exceeding initial capacity with a massive number of insertions | The map should use a sufficiently large fixed array size or implement dynamic resizing to maintain average constant time complexity. |