Build a hash map with no built-in one: hash each key to a bucket, keep a short list there, and update or remove in place.
▼The problem
LeetCode 706 (Easy). Design a MyHashMap without any built-in hash table: put(key, value) inserts or updates, get(key) returns the value or -1 if the key is absent, and remove(key) deletes the key if present. Keys and values are in 0..10^6 (at most 10^4 calls).
Example (LeetCode's): put(1, 1), put(2, 2), get(1) → 1, get(3) → -1, put(2, 1) (overwrite), get(2) → 1, remove(2), get(2) → -1.
The solution
class MyHashMap:
def __init__(self, B=1000):
self.buckets = [[] for _ in range(B)]
def _bucket(self, key):
return self.buckets[key % len(self.buckets)]
def put(self, key, value):
bucket = self._bucket(key)
for pair in bucket:
if pair[0] == key:
pair[1] = value
return
bucket.append([key, value])
def get(self, key):
for k, v in self._bucket(key):
if k == key:
return v
return -1
def remove(self, key):
bucket = self._bucket(key)
bucket[:] = [p for p in bucket if p[0] != key]Transcript
Design HashMap. Build a map from keys to values without a built-in hash table. Put stores a value under a key, or replaces the old one. Get returns a key's value, or minus one if it's missing. Remove deletes a key. Keys run from zero to a million.
For example, we put one, one, then two, two. Getting one returns one. Getting three returns minus one, since three isn't stored. Putting two, one replaces the value, so getting two returns one. After removing two, getting two returns minus one.
The simplest map is one long list of pairs, where every call walks the whole list: order n per call. Or give every possible key its own slot: one step per call, but a million and one slots, nearly all empty.
The fix sits in between: a coat check with a row of hooks, say seven. Twelve goes to hook twelve mod seven, which is five, so a call checks one hook. Two keys can share a hook, like one and eight, so each hook holds a short chain of pairs.
In code, start with a thousand empty buckets. A key's bucket is key mod the number of buckets. Put walks that bucket: if the key is there, it updates the value; if not, it appends a new pair. Get walks the bucket and returns the value, or minus one. Remove keeps every pair except that key.
Now the example on seven hooks. One and two hang on hooks one and two. Getting one checks hook one: one. Getting three finds hook three empty: minus one. Putting two, one updates two in place, so getting two returns one. Removing two takes it off, and getting two returns minus one.
With n pairs, each chain holds about n over the bucket count. Keep enough buckets and the chains stay short, so every call is constant time on average. Space is the buckets plus the pairs.
Pick a hook, check a short chain, update in place. That's Design HashMap.