Design HashMap - Problem
Design a HashMap without using any built-in hash table libraries.
Implement the MyHashMap class:
MyHashMap()initializes the object with an empty map.void put(int key, int value)inserts a(key, value)pair into the HashMap. If the key already exists in the map, update the corresponding value.int get(int key)returns the value to which the specified key is mapped, or-1if this map contains no mapping for the key.void remove(int key)removes the key and its corresponding value if the map contains the mapping for the key.
Input & Output
Example 1 — Basic Operations
$
Input:
operations = ["MyHashMap","put","put","get","get","put","get","remove","get"], values = [[],[1,1],[2,2],[1],[3],[2,1],[2],[2],[2]]
›
Output:
[null,null,null,1,null,null,1,null,-1]
💡 Note:
Create empty hashmap, put(1,1), put(2,2), get(1)→1, get(3)→null, put(2,1), get(2)→1, remove(2), get(2)→-1
Example 2 — Key Updates
$
Input:
operations = ["MyHashMap","put","get","put","get"], values = [[],[5,10],[5],[5,20],[5]]
›
Output:
[null,null,10,null,20]
💡 Note:
put(5,10) stores key 5 with value 10, get(5) returns 10, put(5,20) updates key 5 to value 20, get(5) returns 20
Example 3 — Non-existent Keys
$
Input:
operations = ["MyHashMap","get","remove","get"], values = [[],[1],[2],[1]]
›
Output:
[null,-1,null,-1]
💡 Note:
Empty hashmap: get(1) returns -1 (not found), remove(2) does nothing, get(1) still returns -1
Constraints
- 0 ≤ key, value ≤ 106
- At most 104 calls will be made to put, get, and remove.
Visualization
Tap to expand
Understanding the Visualization
1
Input Operations
Sequence of put/get/remove operations with key-value pairs
2
Hash Function
Map keys to bucket indices using key % bucket_size
3
Result Array
Return values for get operations, null for put/remove
Key Takeaway
🎯 Key Insight: Hash function provides O(1) average access by mapping keys directly to bucket indices
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code