Design HashMap — Chaining with Linked Lists
Advertisement
Problem 192 · Design HashMap
Difficulty: Medium · Pattern: Custom Hash Table
Implement put, get, remove without built-in hash map.
Solutions
# Python — array of buckets (chaining)
class MyHashMap:
def __init__(self):
self.size = 1009 # prime
self.buckets = [[] for _ in range(self.size)]
def _hash(self, key): return key % self.size
def put(self, key, val):
b = self.buckets[self._hash(key)]
for i, (k, v) in enumerate(b):
if k == key: b[i] = (key, val); return
b.append((key, val))
def get(self, key):
for k, v in self.buckets[self._hash(key)]:
if k == key: return v
return -1
def remove(self, key):
h = self._hash(key)
self.buckets[h] = [(k,v) for k,v in self.buckets[h] if k != key]
// Java
class MyHashMap {
private static final int SIZE = 1009;
private LinkedList<int[]>[] map;
public MyHashMap() { map = new LinkedList[SIZE]; }
private int hash(int key) { return key % SIZE; }
public void put(int key, int val) {
int h = hash(key);
if (map[h] == null) map[h] = new LinkedList<>();
for (int[] pair : map[h]) if (pair[0]==key) { pair[1]=val; return; }
map[h].add(new int[]{key, val});
}
public int get(int key) {
int h = hash(key);
if (map[h] == null) return -1;
for (int[] pair : map[h]) if (pair[0]==key) return pair[1];
return -1;
}
public void remove(int key) {
int h = hash(key);
if (map[h] != null) map[h].removeIf(p -> p[0]==key);
}
}
Complexity
- Time: O(n/b) average per operation (b = buckets, n = elements)
- Space: O(n + b)
Advertisement