706. Design HashMap
Asked at 11Apple55Amazon38Microsoft32Meta20Google17Goldman Sachs48Palo Alto Networks65TikTok58Snowflake54Oracle49LinkedIn32
Problem
Design MyHashMap without built-in hash tables: put(key, value) inserts or updates, get(key) returns the value or −1, and remove(key) deletes the key if present.
Example: put(1,1), put(2,2), get(1) → 1, get(3) → −1, put(2,1), get(2) → 1, remove(2), get(2) → −1
Constraints: keys and values ≤ 10⁶; up to 10⁴ calls.
Array of buckets, each a list of [key, value] pairs (separate chaining). Index = key % buckets. Real implementations also resize when the load factor gets high.
Complexity: O(1) average, O(n/buckets) worst per bucket.
class MyHashMap:
def __init__(self):
self.size = 1009 # prime number of buckets
self.b = [[] for _ in range(self.size)]
def put(self, key: int, value: int) -> None:
bucket = self.b[key % self.size]
for pair in bucket:
if pair[0] == key:
pair[1] = value
return
bucket.append([key, value])
def get(self, key: int) -> int:
for k, v in self.b[key % self.size]:
if k == key:
return v
return -1
def remove(self, key: int) -> None:
bucket = self.b[key % self.size]
for i, (k, _) in enumerate(bucket):
if k == key:
bucket.pop(i)
return
hm = MyHashMap()
hm.put(1, 1); hm.put(2, 2)
assert hm.get(1) == 1 and hm.get(3) == -1
hm.put(2, 1); assert hm.get(2) == 1
hm.remove(2); assert hm.get(2) == -1
hm.put(1009 + 1, 7); assert hm.get(1) == 1 and hm.get(1010) == 7 # same bucket
class MyHashMap {
private static final int SIZE = 1009;
private final List<int[]>[] b;
@SuppressWarnings("unchecked")
public MyHashMap() {
b = new List[SIZE];
for (int i = 0; i < SIZE; i++) b[i] = new LinkedList<>();
}
public void put(int key, int value) {
for (int[] p : b[key % SIZE]) if (p[0] == key) { p[1] = value; return; }
b[key % SIZE].add(new int[]{key, value});
}
public int get(int key) {
for (int[] p : b[key % SIZE]) if (p[0] == key) return p[1];
return -1;
}
public void remove(int key) { b[key % SIZE].removeIf(p -> p[0] == key); }
}
type MyHashMap struct {
b [][][2]int // separate chaining: buckets of (key, value)
}
const buckets = 1009 // a prime number of buckets
func Constructor() MyHashMap {
return MyHashMap{b: make([][][2]int, buckets)}
}
func (this *MyHashMap) Put(key int, value int) {
b := this.b[key%buckets]
for i := range b {
if b[i][0] == key {
b[i][1] = value
return
}
}
this.b[key%buckets] = append(b, [2]int{key, value})
}
func (this *MyHashMap) Get(key int) int {
for _, kv := range this.b[key%buckets] {
if kv[0] == key {
return kv[1]
}
}
return -1
}
func (this *MyHashMap) Remove(key int) {
b := this.b[key%buckets]
for i := range b {
if b[i][0] == key {
this.b[key%buckets] = append(b[:i], b[i+1:]...)
return
}
}
}