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
.For example:
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]
What are the time and space complexities of each operation, and how do you handle collisions?
# MyHashMap Implementation
This response provides an implementation of a HashMap without using any built-in hash table libraries. The implementation utilizes an array of linked lists (buckets) to handle collisions. Each bucket stores key-value pairs. The hash function maps keys to indices within the array.
## Code Implementation
```python
class MyHashMap:
def __init__(self):
"""
Initialize your data structure here.
"""
self.capacity = 1000 # Initial capacity of the hash map
self.table = [None] * self.capacity # Array of linked lists (buckets)
def _hash(self, key):
"""Hashes the key to an index in the hash table.
A simple hash function to convert the key into an index.
"""
return key % self.capacity
def put(self, key: int, value: int) -> None:
"""
Inserts a (key, value) pair into the HashMap.
If the key already exists in the map, update the corresponding value.
"""
index = self._hash(key)
if self.table[index] is None:
self.table[index] = [] # Create a new list (bucket)
for i, (k, v) in enumerate(self.table[index]):
if k == key:
self.table[index][i] = (key, value) # Update existing key
return
self.table[index].append((key, value)) # Add new key-value pair
def get(self, key: int) -> int:
"""
Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key.
"""
index = self._hash(key)
if self.table[index] is None:
return -1 # Key not found
for k, v in self.table[index]:
if k == key:
return v # Key found, return value
return -1 # Key not found
def remove(self, key: int) -> None:
"""
Removes the key and its corresponding value if the map contains the mapping for the key.
"""
index = self._hash(key)
if self.table[index] is None:
return # Key not found
self.table[index] = [(k, v) for k, v in self.table[index] if k != key]
# Example Usage
myHashMap = MyHashMap()
myHashMap.put(1, 1)
myHashMap.put(2, 2)
print(myHashMap.get(1)) # Output: 1
print(myHashMap.get(3)) # Output: -1
myHashMap.put(2, 1)
print(myHashMap.get(2)) # Output: 1
myHashMap.remove(2)
print(myHashMap.get(2)) # Output: -1
Initialization:
__init__
method initializes the HashMap with a fixed capacity (e.g., 1000). It creates a list (array) named table
of the specified capacity, where each element is initially None
. This table will hold the buckets. Each bucket is essentially a linked list (implemented via a Python list for simplicity) that stores key-value pairs. This handles collision.Hash Function:
_hash
method takes a key as input and returns an index within the table
. This is a crucial part of the HashMap as it determines where a key-value pair will be stored. A simple modulo operation (key % self.capacity
) is used to map the key to an index. Good hash function minimize collision.Put (Insert/Update):
put
method inserts a key-value pair into the HashMap. It first calculates the index using the _hash
method. Then, it checks if a bucket exists at that index.
Get (Retrieve):
get
method retrieves the value associated with a given key. It calculates the index using the _hash
method and checks if a bucket exists at that index.
Remove (Delete):
remove
method removes a key-value pair from the HashMap. It calculates the index using the _hash
method and checks if a bucket exists at that index.
put
, the average case is constant time if keys are evenly distributed.Hash Collisions:
Large Number of Keys:
Negative Keys:
abs(key) % capacity
.Non-Integer Keys: