Design Hashmap Problem
Description
LeetCode Problem 706.
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 <= 10^6
- At most 10^4 calls will be made to put, get, and remove.
Solution
Approach: Buckets with Separate Chaining
A hash map spreads its entries over a fixed number of buckets, so that each operation only looks at a few entries instead of all of them.
- Hash:
key % BUCKETS, withBUCKETS = 1009. A prime number of buckets spreads keys evenly even when they follow a pattern such as all multiples of 10. - Bucket: a small list of
(key, value)pairs whose keys share a hash. Colliding keys are stored side by side (separate chaining).
Each operation finds the bucket of key and scans only that list:
- put(key, value): if a pair with
keyis already in the bucket, overwrite its value; otherwise append a new pair. - get(key): return the value of the pair with
key, or-1if there is none. - remove(key): delete the pair with
keyif it is there.
The step people get wrong is put on an existing key. Appending a second pair instead of updating the first breaks things later: get may return the old value, and after remove deletes one copy, the other is still found.
With at most 104 keys over 1009 buckets, each bucket holds about 10 pairs on average. (Since keys are at most 106, an array of size 106 + 1 filled with -1 would also pass, but it does not show how a hash map works.)
Complexity: O(n / b) average time per operation, where n is the number of stored keys and b = 1009 is the number of buckets. O(b + n) space.
class MyHashMap:
# A prime number of buckets spreads keys evenly; at most 10^4 keys gives about 10 per bucket.
BUCKETS = 1009
def __init__(self):
self.buckets = [[] for _ in range(self.BUCKETS)] # bucket i holds [key, value] pairs with hash i
def _bucket(self, key: int) -> List[List[int]]:
return self.buckets[key % self.BUCKETS]
def put(self, key: int, value: int) -> None:
bucket = self._bucket(key)
for entry in bucket:
if entry[0] == key:
entry[1] = value # key already there: update it
return
bucket.append([key, value])
def get(self, key: int) -> int:
for entry in self._bucket(key):
if entry[0] == key:
return entry[1]
return -1
def remove(self, key: int) -> None:
bucket = self._bucket(key)
for i, entry in enumerate(bucket):
if entry[0] == key:
bucket.pop(i)
return
Now write it from memory
Close the write-up and solve it yourself against the tests.