Design HashMap
Problem
Design a HashMap without using any built-in hash table libraries. Implement the methods put(key, value), get(key), and remove(key) to store, retrieve, and delete key-value pairs respectively.
- 0 ≤ key, value ≤ 10⁶
- At most 10⁴ calls will be made to put, get, and remove.
Example
put(1, 1), put(2, 2), get(1), get(3), put(2, 1), get(2), remove(2), get(2)[null, null, 1, -1, null, 1, null, -1]Initially, the map is empty. put(1,1) inserts key 1 with value 1. put(2,2) inserts key 2 with value 2. get(1) returns 1. get(3) returns -1 since key 3 does not exist. put(2,1) updates key 2's value to 1. get(2) returns 1. remove(2) deletes key 2. get(2) returns -1 since key 2 was removed.
Approach
Straightforward Solution
A naive approach uses a large array indexed by key, but this is infeasible due to memory constraints and sparse keys. Another naive approach is to store all pairs in a list and scan linearly, resulting in O(n) operations.
Core Observation
A HashMap stores key-value pairs and supports efficient insertion, retrieval, and deletion. Collisions occur when multiple keys hash to the same bucket, so a collision resolution strategy is necessary.
Path to Optimal
The key recognition signals are 'design a hash map', 'handle collisions', and 'efficient operations'. These indicate using an array of buckets combined with chaining (linked lists or arrays) to handle collisions. The hash function maps keys to bucket indices, and each bucket stores key-value pairs. This approach balances memory and time efficiency.
Optimal Approach
Implement a fixed-size array of buckets (size is a prime number to reduce collisions). Use modulo hashing to map keys to buckets. Each bucket stores a list of key-value pairs. For put, search the bucket for the key and update or append. For get, search and return the value or -1. For remove, search and delete the pair if found. This yields average O(1) time per operation with O(n) space.
Time
O(1) average per operation
With a good hash function and a sufficiently large number of buckets, the average number of elements per bucket remains low, making search, insert, and delete operations average O(1).
Space
O(n)
Space scales linearly with the number of stored key-value pairs, as each pair is stored exactly once in a bucket list.
Pattern Spotlight
Hash Maps (Separate Chaining)
Use a fixed-size array of buckets and resolve collisions by storing all colliding key-value pairs in a list within each bucket; this transforms collision handling into a manageable linear search within a small subset.
Solution
| 1 | class MyHashMap: |
| 2 | |
| 3 | def __init__(self): |
| 4 | self.bucket_count = 1009 |
| 5 | self.buckets = [[] for _ in range(self.bucket_count)] |
| 6 | |
| 7 | def _get_bucket(self, key: int) -> list: |
| 8 | bucket_index = key % self.bucket_count |
| 9 | return self.buckets[bucket_index] |
| 10 | |
| 11 | def put(self, key: int, value: int) -> None: |
| 12 | bucket = self._get_bucket(key) |
| 13 | |
| 14 | for pair in bucket: |
| 15 | if pair[0] == key: |
| 16 | pair[1] = value |
| 17 | return |
| 18 | |
| 19 | bucket.append([key, value]) |
| 20 | |
| 21 | def get(self, key: int) -> int: |
| 22 | bucket = self._get_bucket(key) |
| 23 | |
| 24 | for stored_key, stored_value in bucket: |
| 25 | if stored_key == key: |
| 26 | return stored_value |
| 27 | |
| 28 | return -1 |
| 29 | |
| 30 | def remove(self, key: int) -> None: |
| 31 | bucket = self._get_bucket(key) |
| 32 | |
| 33 | for index, pair in enumerate(bucket): |
| 34 | if pair[0] == key: |
| 35 | bucket.pop(index) |
| 36 | return |
Step-by-Step Solution
Initialize Buckets Array with Fixed Size for Hashing
| 4 | self.bucket_count = 1009 |
| 5 | self.buckets = [[] for _ in range(self.bucket_count)] |
Objective
To create a fixed-size array of empty buckets to store key-value pairs and define the bucket count for hashing.
Key Insight
Choosing a prime number for bucket count reduces clustering and distributes keys more evenly across buckets. Initializing each bucket as an empty list prepares the structure for separate chaining, enabling efficient collision handling by storing multiple pairs in the same bucket.
Interview Quick-Check
Core Logic
Using a fixed-size array of buckets with separate chaining enables average O(1) operations by limiting collision scope.
Common Pitfalls & Bugs
Choosing a poor bucket count (e.g., a power of two) can increase collisions and degrade performance.
Map Keys to Buckets Using Modulo Hash Function
| 7 | def _get_bucket(self, key: int) -> list: |
| 8 | bucket_index = key % self.bucket_count |
| 9 | return self.buckets[bucket_index] |
Objective
To compute the bucket index for any given key using modulo operation.
Key Insight
The modulo operation with the bucket count maps keys uniformly into the bucket array indices. This simple hash function is efficient and effective for integer keys, ensuring that keys are distributed across buckets to minimize collisions.
Interview Quick-Check
Core Logic
The modulo hash function transforms a key into a bucket index, enabling constant-time access to the relevant bucket.
Common Pitfalls & Bugs
Failing to use modulo or using an inappropriate hash function can cause uneven bucket distribution and performance degradation.
Insert or Update Key-Value Pair in Appropriate Bucket
| 12 | bucket = self._get_bucket(key) |
| 14 | for pair in bucket: |
| 15 | if pair[0] == key: |
| 16 | pair[1] = value |
| 17 | return |
| 19 | bucket.append([key, value]) |
Objective
To add a new key-value pair or update an existing key's value within the correct bucket.
Key Insight
By searching the bucket's list for the key, the algorithm ensures that duplicate keys are updated rather than duplicated. If the key is not found, appending the new pair maintains the bucket's integrity. This approach preserves correctness and supports efficient updates.
Interview Quick-Check
Core Logic
Searching the bucket for the key before insertion prevents duplicates and ensures updates happen in place.
State & Boundaries
If the key is found, update and return immediately to avoid unnecessary appends.
Common Pitfalls & Bugs
Appending without checking for existing keys leads to duplicate entries and incorrect behavior.
Retrieve Value by Searching Bucket for Key
| 22 | bucket = self._get_bucket(key) |
| 24 | for stored_key, stored_value in bucket: |
| 25 | if stored_key == key: |
| 26 | return stored_value |
| 28 | return -1 |
Objective
To find and return the value associated with a key by searching its bucket, or return -1 if not found.
Key Insight
Searching only the relevant bucket limits the search scope, making retrieval efficient. Returning -1 when the key is absent clearly signals a missing entry, matching the problem specification.
Interview Quick-Check
Core Logic
Lookup is performed by scanning the bucket for the key, returning the associated value immediately upon match.
State & Boundaries
Returning -1 when the key is not found distinguishes missing keys from valid stored values.
Remove Key-Value Pair by Locating and Deleting from Bucket
| 31 | bucket = self._get_bucket(key) |
| 33 | for index, pair in enumerate(bucket): |
| 34 | if pair[0] == key: |
| 35 | bucket.pop(index) |
| 36 | return |
Objective
To delete a key-value pair from the bucket by locating the key and removing its entry.
Key Insight
Enumerating the bucket allows direct access to the index of the key-value pair, enabling efficient removal. Early return after removal prevents unnecessary iteration and maintains correctness.
Interview Quick-Check
Core Logic
Enumerating the bucket provides the index needed to remove the key-value pair efficiently.
State & Boundaries
Returning immediately after removal avoids redundant operations and preserves expected behavior.
Common Pitfalls & Bugs
Failing to remove the correct pair or continuing iteration after removal can cause errors or inefficiency.
Line Analysis
This solution has 9 Critical lines interviewers watch for.
self.buckets = [[] for _ in range(self.bucket_count)]
Initialize the buckets as a list of empty lists for separate chaining.
Each bucket is an independent list that stores key-value pairs, enabling collision resolution by chaining multiple pairs in the same bucket.
bucket_index = key % self.bucket_count
Calculate the bucket index by taking key modulo bucket count.
Modulo operation maps keys to valid bucket indices, ensuring keys are distributed within the fixed bucket array.
if pair[0] == key:
Check if the current pair's key matches the input key.
Identifying the correct pair is necessary to update its value instead of appending a duplicate.
pair[1] = value
Update the value of the existing key-value pair.
In-place update preserves the bucket structure and ensures the latest value is stored for the key.
if stored_key == key:
Check if the current pair's key matches the input key.
Matching the key is necessary to return the correct associated value.
return stored_value
Return the value associated with the found key.
Returning immediately upon finding the key optimizes lookup time and correctness.
for index, pair in enumerate(bucket):
Enumerate the bucket to get index and key-value pairs for removal.
Enumerating allows direct access to the index needed for efficient removal from the list.
if pair[0] == key:
Check if the current pair's key matches the input key.
Identifying the correct pair is essential to remove the intended key-value pair without affecting others.
bucket.pop(index)
Remove the key-value pair from the bucket by index.
Removing by index is efficient and maintains the bucket's integrity after deletion.
self.bucket_count = 1009
Set the number of buckets to a prime number for better key distribution.
Choosing a prime number for bucket count reduces clustering and helps distribute keys more uniformly across buckets, improving average operation time.
def put(self, key: int, value: int) -> None:
Retrieve the bucket for the given key before insertion or update.
All put operations must operate on the correct bucket to maintain data integrity and performance.
for pair in bucket:
Iterate over each key-value pair in the bucket to find if the key exists.
Searching the bucket ensures that updates modify existing keys rather than creating duplicates.
return
Return immediately after updating to avoid duplicate entries.
Early return prevents appending a new pair after updating, maintaining correctness.
bucket.append([key, value])
Append a new key-value pair to the bucket if the key was not found.
Adding new pairs to the bucket handles insertions and collision resolution via chaining.
def get(self, key: int) -> int:
Retrieve the bucket for the given key before lookup.
Lookup operations must access the correct bucket to find the key efficiently.
for stored_key, stored_value in bucket:
Iterate over each key-value pair in the bucket to find the key.
Searching the bucket limits the lookup scope to a small subset, enabling efficient retrieval.
return -1
Return -1 if the key is not found in the bucket.
Returning -1 signals the absence of the key, conforming to the problem specification.
def remove(self, key: int) -> None:
Retrieve the bucket for the given key before removal.
Removal operations must target the correct bucket to find and delete the key-value pair.
return
Return immediately after removal to avoid unnecessary iteration.
Early return ensures the method completes promptly after successful deletion, preserving expected behavior.
return self.buckets[bucket_index]
Return the bucket list corresponding to the computed index.
Accessing the correct bucket is essential for all operations to target the right subset of key-value pairs.
def _get_bucket(self, key: int) -> list:
Define a helper method to compute the bucket for a given key.
Encapsulating the hash function logic improves code clarity and reuse, centralizing the bucket computation.
bucket = self._get_bucket(key)
Assign the bucket to a local variable for iteration.
Local reference simplifies subsequent operations and improves readability.
bucket = self._get_bucket(key)
Assign the bucket to a local variable for iteration.
Local reference simplifies the search process and improves code clarity.
bucket = self._get_bucket(key)
Assign the bucket to a local variable for iteration.
Local reference facilitates enumeration and removal operations.
Test Your Understanding
Why is separate chaining with a fixed-size bucket array an effective collision resolution strategy for a hash map?
Because it confines collisions to small lists within buckets, allowing constant-time average operations by limiting the search scope to a small subset rather than the entire data set.
Related Problems
Hash Maps pattern
Don't just read it. Drill it.
Reconstruct Design HashMap from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.
Unlock the Design HashMap drill