call(back)
Algorithms & Data StructuresmediumSign in to star problems

Design HashMap

Implement a hash map with put(key, value), get(key) and remove(key) without using any built-in hash table (no Map, Set, dict or plain-object-as-map for the storage itself). Keys are non-negative integers; get returns -1 for a missing key.

map = MyHashMap()
map.put(1, 1); map.put(2, 2)
map.get(1)    ->  1
map.get(3)    ->  -1
map.put(2, 1)             // update
map.get(2)    ->  1
map.remove(2)
map.get(2)    ->  -1

Keep operations O(1) amortised as the map grows: resize when the load factor passes a threshold.

Hints

Hint 1

Separate chaining: an array of buckets, each a small list of [key, value] pairs, indexed by key modulo the capacity. put scans the bucket for an existing key before appending; get and remove scan the same bucket.

Hint 2

Track the entry count and double the bucket array when count exceeds 0.75 × capacity, re-inserting every pair under the new modulus. Mask or otherwise force the hash non-negative before taking the modulo.

Asked at