Design a HashMap without using any built-in hash table libraries. Implement the following operations:
put(key: int, value: int) -> None
: Insert a (key, value)
pair into the HashMap. If the key
already exists, update the corresponding value
.get(key: int) -> int
: Return the value
to which the specified key
is mapped, or -1
if the HashMap contains no mapping for the key
.remove(key: int) -> None
: Remove the mapping for the specified key
if it exists.Example:
MyHashMap hashMap = new MyHashMap();
hashMap.put(1, 1);
hashMap.put(2, 2);
hashMap.get(1); // returns 1
hashMap.get(3); // returns -1 (not found)
hashMap.put(2, 1); // update the existing value
hashMap.get(2); // returns 1
hashMap.remove(2); // remove the mapping for 2
hashMap.get(2); // returns -1 (not found)
Constraints:
[0, 10^6]
.[1, 10^4]
.(key, value)
pair.-1
.class MyHashMap:
def __init__(self):
# Define the number of buckets
self.size = 1000
self.buckets = [[] for _ in range(self.size)]
def _hash(self, key: int) -> int:
return key % self.size
def put(self, key: int, value: int) -> None:
hash_key = self._hash(key)
for idx, (k, v) in enumerate(self.buckets[hash_key]):
if k == key:
self.buckets[hash_key][idx] = (key, value)
return
self.buckets[hash_key].append((key, value))
def get(self, key: int) -> int:
hash_key = self._hash(key)
for k, v in self.buckets[hash_key]:
if k == key:
return v
return -1
def remove(self, key: int) -> None:
hash_key = self._hash(key)
bucket = self.buckets[hash_key]
for idx, (k, v) in enumerate(bucket):
if k == key:
del bucket[idx]
return
This design leverages an array of linked lists (or vectors) and provides average constant-time complexity for basic operations, assuming a good hash function and a large enough array.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?