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 -1 if 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
Design HashMap: Custom Hash Table ImplementationOperationsput(1,10)put(2,20)get(1)remove(2)Hash Table (Buckets)(1,10)(2,20)[ ][ ][1][2][3][0]Resultsnull (put)null (put)10 (get)null (remove)Hash Function: key % 4 determines bucket indexput(1,10): 1%4=1 → bucket[1], put(2,20): 2%4=2 → bucket[2]get(1): 1%4=1 → bucket[1] → return 10Time: O(1) average per operation, Space: O(n) for n key-value pairs
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
Asked in
Amazon 45 Google 38 Microsoft 32 Facebook 28
78.4K Views
High Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen