LeetCode #706 Easy

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 if key is already stored.
  • get(key) returns the value for key, or -1 if it is absent.
  • remove(key) deletes key and 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.

Constraints
  • 0 <= key, value <= 10⁶
  • At most 10⁴ calls will be made to put, get, and remove.
hash-tabledesignlinked-list
Open on LeetCode ↗
02

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 % 1009 picks 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.

How to spot this pattern

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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

04

Code in Python, C++ and Java

▶1class MyHashMap:
▶2 def __init__(self):
▶3 self.size = 1009
▶4 self.buckets = [[] for _ in range(self.size)]
▶5 
▶6 def put(self, key: int, value: int) -> None:
▶7 bucket = self.buckets[key % self.size]
▶8 for pair in bucket:
▶9 if pair[0] == key:
▶10 pair[1] = value
▶11 return
▶12 bucket.append([key, value])
▶13 
▶14 def get(self, key: int) -> int:
▶15 for k, v in self.buckets[key % self.size]:
▶16 if k == key:
▶17 return v
▶18 return -1
▶19 
▶20 def remove(self, key: int) -> None:
▶21 bucket = self.buckets[key % self.size]
▶22 for i, pair in enumerate(bucket):
▶23 if pair[0] == key:
▶24 bucket.pop(i)
▶25 return
keyvalcallput(1, 1)bucket1%1009=1buckets1112empty3emptyother buckets emptyget returnednone yetbucket 1 empty → append 1, 1
bucket1
chain length1
1 % 1009 = 1, so only bucket 1 can hold key 1. The bucket has no pairs, so key 1 is new: append the pair.
keyvalcallput(2, 2)bucket2%1009=2buckets1112223emptyother buckets emptyget returnednone yetbucket 2 empty → append 2, 2
bucket2
chain length1
2 % 1009 = 2, so only bucket 2 can hold key 2. The bucket has no pairs, so key 2 is new: append the pair.
keyvalcallget(1)bucket1%1009=1buckets1112223emptyother buckets emptyget returned1key 1 found → return 1
bucket1
returns1
1 % 1009 = 1, so only bucket 1 can hold key 1. This pair has key 1, so return its value 1. Each key appears at most once in its bucket, so the scan can stop here.
keyvalcallget(3)bucket3%1009=3buckets1112223emptyother buckets emptyget returned1-1bucket 3 empty → return -1
bucket3
returns-1
3 % 1009 = 3, so only bucket 3 can hold key 3. Nothing is stored in this bucket. The key is absent, so return -1; stored values are never negative, so -1 cannot be mistaken for one.
keyvalcallput(2, 1)bucket2%1009=2buckets1112213emptyother buckets emptyget returned1-1key 2 found → value 2 → 1
bucket2
value2 → 1
2 % 1009 = 2, so only bucket 2 can hold key 2. Key 2 is already stored, so overwrite its value in place and stop. Appending a second pair would leave the old value behind for get to find.
keyvalcallget(2)bucket2%1009=2buckets1112213emptyother buckets emptyget returned1-11key 2 found → return 1
bucket2
returns1
2 % 1009 = 2, so only bucket 2 can hold key 2. This pair has key 2, so return its value 1. Each key appears at most once in its bucket, so the scan can stop here.
keyvalcallremove(2)bucket2%1009=2buckets1112empty3emptyother buckets emptyget returned1-11key 2 found → pair removed
bucket2
removed2 → 1
2 % 1009 = 2, so only bucket 2 can hold key 2. This pair has key 2, so delete it from the list and stop. Bucket 2 is empty again.
keyvalcallget(2)bucket2%1009=2buckets1112empty3emptyother buckets emptyget returned1-11-1bucket 2 empty → return -1
bucket2
returns-1
2 % 1009 = 2, so only bucket 2 can hold key 2. Nothing is stored in this bucket. The key is absent, so return -1; stored values are never negative, so -1 cannot be mistaken for one.
05

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.

▶1class MyHashMap:
▶2 def __init__(self):
▶3 self.data = [-1] * 1000001
▶4 
▶5 def put(self, key: int, value: int) -> None:
▶6 self.data[key] = value
▶7 
▶8 def get(self, key: int) -> int:
▶9 return self.data[key]
▶10 
▶11 def remove(self, key: int) -> None:
▶12 self.data[key] = -1
06

Common pitfalls

Overwriting an entire collision bucket

✗ Wrong
self.buckets[key % self.bucket_count] = [key, value]
✓ Right
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

✗ Wrong
bucket.append([key, value])
✓ Right
pair[1] = value

When the key already exists, put must update it. Appending leaves two conflicting values for one key.

07

Complexity

Time
O(n / B) average per call
Space
O(n + B)
n is the number of stored keys and B = 1009 buckets, so a chain holds n / B pairs on average. If every key hashed to the same bucket, one call would scan all n pairs.
08

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.