Design HashMap
Design HashMap is LeetCode 706 (Easy). Build a MyHashMap class without using any built-in hash table library:
put(key, value)inserts the pair, or updates the value ifkeyis already stored.get(key)returns the value forkey, or-1if it is absent.remove(key)deleteskeyand its value if present.
Keys and values lie between 0 and 10⁶, and there are at most 10⁴ calls, so at most 10⁴ keys are ever stored.
- 0 <= key, value <= 10⁶
- At most 10⁴ calls will be made to put, get, and remove.
Intuition
A hash map turns a key into an array index, so a lookup jumps straight to one small spot instead of scanning everything. Here the index is key % 1009, called the key's bucket.
Different keys can land in the same bucket, so each bucket holds a short list of [key, value] pairs. This is separate chaining:
- Hash:
key % 1009picks the bucket. - Chain: the bucket's list holds every pair that hashed there, and comparing the full key tells them apart.
- Short chains: at most 10⁴ keys over 1009 buckets is about 10 pairs per bucket, so each scan is quick.
A prime bucket count also spreads out keys that share a pattern, such as all multiples of 8, instead of piling them into a few buckets.
When a problem asks you to build a map rather than use one, it is testing two ideas: a hash function that picks a small search area, and collision handling so keys that share a bucket do not overwrite each other.
Approach
Before reading on, decide how many buckets to use and what each bucket stores. Then work out what put must check before it adds a pair. Aim for a short scan per call.
Two ways to solve it
Hash each key to one of 1009 buckets and keep a short list of pairs in each.
- Memory: grows with the keys actually stored.
- General: works for any key range.
- Cost: each call scans one short chain.
The design the problem is testing.
Use the key itself as the index into an array of 10⁶ + 1 slots, with -1 meaning empty.
- Fastest: every call is one array access.
- Memory: a million slots, even for one key.
- Limit: works only because keys are small integers.
Fine when the key range is small and known.
The array is quicker per call, but it reserves a slot for every possible key and only works because keys stay below 10⁶; chaining uses memory in proportion to what is stored, which is what a hash map is for. The steps, code and live demo follow chaining, and the array code comes after the demo.
Create the buckets
Make 1009 empty lists, one per bucket. The problem caps the number of keys, so the count can stay fixed and the table never needs to grow.
Put: update or append
Go to bucket key % 1009 and scan its pairs. If one has this key, overwrite its value and stop; if none does, append [key, value]. Each key then appears at most once in its bucket, so get and remove can stop at the first match.
Get: scan one bucket
Scan the key's bucket and return the value of the pair with this key. If the scan ends without a match, return -1. Stored values are never negative, so -1 cannot be mistaken for a real value.
Remove: delete the matching pair
Scan the key's bucket, delete the pair with this key and stop. If no pair matches, do nothing. The other pairs in the bucket are untouched.
Code in Python, C++ and Java
get to find.Plain array
Every possible key from 0 to 10⁶ gets its own slot, so put, get and remove are single array accesses. Empty slots hold -1 rather than 0, because 0 is a valid value.
Common pitfalls
Overwriting an entire collision bucket
self.buckets[key % self.bucket_count] = [key, value]
bucket.append([key, value])
Replacing the whole bucket throws away every other key stored in it: after put(1, 10) and put(1010, 20), get(1) returns -1.
Appending a duplicate mapping
bucket.append([key, value])
pair[1] = value
When the key already exists, put must update it. Appending leaves two conflicting values for one key.
Complexity
Design HashMap FAQ
What does the Java version use instead of java.util.HashMap?
Use an array of 1009 LinkedList<int[]> buckets, where each int[] is a {key, value} pair. Java cannot create a generic array directly, so new List[1009] gives an unchecked warning, which is harmless here. remove deletes through an Iterator, the safe way to remove an element in the middle of a scan.
How is Design HashMap different from Design HashSet?
Design HashSet (LeetCode 705) stores keys only and answers contains with true or false. The buckets and the scan are the same; each chain simply holds keys instead of [key, value] pairs, and there is no value to update.