Design HashMap (LeetCode 706): Solution and Explanation
Build an integer-to-integer map with put, get and remove without any built-in hash table. Keys and values range from 0 to 10^6 and there are at most 10^4 calls, so each call should cost close to O(1).
Intuition
A hash map turns a key into an array index with a cheap rule, here key % 20011. That index is the key's home slot, and the pair is stored there when the slot is free.
Two keys can share a home slot. Instead of hanging a list off each slot, open addressing keeps everything in one flat array: if the home slot is taken by another key, step to the next slot, and keep stepping until you reach the key or an empty slot. This is linear probing.
The same walk answers every question. put writes wherever the walk stops, get reads the value if the walk stopped on the key, and an empty slot proves the key is absent because it would have been placed no later than there.
Removal is the subtle part. Emptying a slot would cut a probe run in half, and a key stored after it would become unreachable. So remove leaves a tombstone, a marker that says the slot is no longer used but the search must keep going.
The table size 20011 is a prime about twice the number of keys that can ever be stored, so the table stays at most half full and probe runs stay short.
Approach: Open addressing with linear probing and tombstones
- Create
keysof size 20011 filled with -1 (empty) andvalsof the same size. find(key): start atkey % 20011and move to the next slot (wrapping at the end) while the slot is neither empty nor holdingkey. Return the slot where the walk stops.put(key, value): writekeyandvalueatfind(key). That slot either already holds the key (update) or is the first empty slot of the run (insert).get(key): returnvals[i]ifkeys[i] == keyati = find(key), otherwise -1.remove(key): iffind(key)lands on the key, set that slot to -2, a tombstone that later walks step over.
Step-by-step example
commands = ["MyHashMap","put","put","put","remove","get","put","get"], values = [[],[5,50],[20016,60],[40027,70],[20016],[40027],[20016,61],[20016]]
- All three keys have home slot 5, because 20016 = 20011 + 5 and 40027 = 2 * 20011 + 5.
put(5, 50)stores at slot 5.put(20016, 60)finds slot 5 taken by 5 and probes to slot 6.put(40027, 70)steps over slots 5 and 6 and lands in slot 7.remove(20016)probes to slot 6 and marks it as a tombstone instead of emptying it.get(40027)walks 5, then the tombstone at 6, and finds 40027 at slot 7, returning 70. Had slot 6 been emptied, the walk would have stopped there and wrongly returned -1.put(20016, 61)walks past the tombstone to the empty slot 8 and stores the pair there, andget(20016)returns 61. Output: [null,null,null,null,null,70,null,61].
Code: Python, Java, C++
1class MyHashMap:
2 def __init__(self):
3 self.size = 20011
4 self.keys = [-1] * self.size # -1 = empty, -2 = deleted
5 self.vals = [0] * self.size
6
7 def _find(self, key: int) -> int:
8 i = key % self.size
9 while self.keys[i] != -1 and self.keys[i] != key:
10 i = (i + 1) % self.size
11 return i
12
13 def put(self, key: int, value: int) -> None:
14 i = self._find(key)
15 self.keys[i] = key
16 self.vals[i] = value
17
18 def get(self, key: int) -> int:
19 i = self._find(key)
20 return self.vals[i] if self.keys[i] == key else -1
21
22 def remove(self, key: int) -> None:
23 i = self._find(key)
24 if self.keys[i] == key:
25 self.keys[i] = -21class MyHashMap {
2 private static final int SIZE = 20011;
3 private int[] keys = new int[SIZE];
4 private int[] vals = new int[SIZE];
5
6 public MyHashMap() {
7 Arrays.fill(keys, -1); // -1 = empty, -2 = deleted
8 }
9
10 private int find(int key) {
11 int i = key % SIZE;
12 while (keys[i] != -1 && keys[i] != key) {
13 i = (i + 1) % SIZE;
14 }
15 return i;
16 }
17
18 public void put(int key, int value) {
19 int i = find(key);
20 keys[i] = key;
21 vals[i] = value;
22 }
23
24 public int get(int key) {
25 int i = find(key);
26 return keys[i] == key ? vals[i] : -1;
27 }
28
29 public void remove(int key) {
30 int i = find(key);
31 if (keys[i] == key) {
32 keys[i] = -2;
33 }
34 }
35}1class MyHashMap {
2 static const int SIZE = 20011;
3 vector<int> keys;
4 vector<int> vals;
5
6 int find(int key) {
7 int i = key % SIZE;
8 while (keys[i] != -1 && keys[i] != key) {
9 i = (i + 1) % SIZE;
10 }
11 return i;
12 }
13
14public:
15 MyHashMap() {
16 keys.assign(SIZE, -1); // -1 = empty, -2 = deleted
17 vals.assign(SIZE, 0);
18 }
19
20 void put(int key, int value) {
21 int i = find(key);
22 keys[i] = key;
23 vals[i] = value;
24 }
25
26 int get(int key) {
27 int i = find(key);
28 return keys[i] == key ? vals[i] : -1;
29 }
30
31 void remove(int key) {
32 int i = find(key);
33 if (keys[i] == key) {
34 keys[i] = -2;
35 }
36 }
37};Time and space complexity
O(1) average per call
The table is at most about half full, so the expected probe run from any home slot is a small constant. A long run of collisions is possible in theory but does not happen with these limits.
O(m)
Two arrays of m = 20011 integers, independent of how many keys are stored.
Other approaches
Separate chaining (time O(n / b) average per call, space O(b + n))
Keep a fixed number of buckets, each a list of (key, value) pairs, and scan only the key's bucket. Removal is a plain list delete, so there are no tombstones, at the cost of a list allocation per bucket.
Direct-address array (time O(1), space O(max key))
Allocate 10^6 + 1 integers filled with -1 and use the key itself as the index. Every call is one array access, but the memory is fixed at a million entries.
Common mistakes
- Emptying a slot on remove. Any key that probed past that slot becomes unreachable, and
getreturns -1 for a key that is still stored. - Inserting a new copy of a key that already exists further along the run. Using the same
findwalk forputguarantees an existing key is updated in place. - Forgetting to wrap the index with
% size, which walks off the end of the array when a run reaches the last slot. - Choosing a table barely larger than the number of keys. As the load factor approaches 1, probe runs grow sharply and calls slow down.
Frequently asked questions
Why not just reuse a tombstone slot in put?
You can, and it saves space, but you must still check the rest of the run first, because the key may already be stored after the tombstone. Reusing it without that check creates a duplicate key. The simple version here always walks to the key or to an empty slot, which is correct and fast enough at this load.
Do tombstones ever cause trouble?
They make runs longer, since walks treat them as occupied. A long-lived table with many removals rebuilds itself periodically to clear them. With at most 10^4 calls and a table of 20011 slots, runs stay short without a rebuild.
Why is the table size prime?
A prime modulus does not share factors with common key patterns, so keys like multiples of 10 or 1000 still land in different home slots instead of crowding into a few.