[
design
hash table
]
Leetcode 0706. Design HashMap
https://leetcode.com/problems/design-hashmap
This problem is basically the same as Problem 704 Design HashSet, but here we need to keep pairs of elements: key and value. Also we need to modify function put a bit: If the value already exists in the HashMap, update the value, so we check if key is already here and if it, we update its value.
See my explained solution for 704: https://leetcode.com/problems/design-hashset/discuss/768659/Python-Easy-Multiplicative-Hash-explained
All complexities are the same: it is O(1) in average if we assume that probability of collision is small.
class MyHashMap:
def eval_hash(self, key):
return ((key*1031237) & (1<<20) - 1)>>5
def __init__(self):
self.arr = [[] for _ in range(1<<15)]
def put(self, key, value):
t = self.eval_hash(key)
for i,(k,v) in enumerate(self.arr[t]):
if k == key:
self.arr[t][i] = (k, value)
return
self.arr[t].append((key, value))
def get(self, key):
t = self.eval_hash(key)
for i,(k,v) in enumerate(self.arr[t]):
if k == key: return v
return -1
def remove(self, key: int):
t = self.eval_hash(key)
for i,(k,v) in enumerate(self.arr[t]):
if k == key:
self.arr[t].remove((k,v))
If you like the solution, you can upvote it on leetcode discussion section: Problem 0706