Custom Hash Map - Problem

Design a hash map from scratch that supports the following operations:

  • put(key, value): Insert a key-value pair into the hash map. If the key already exists, update its value.
  • get(key): Return the value associated with the key, or -1 if the key doesn't exist.
  • remove(key): Remove the key-value pair from the hash map if it exists.

Your implementation should handle collisions using chaining (linked lists). The hash map should automatically resize when the load factor exceeds 0.75.

Implement the CustomHashMap class with the above methods. For this problem, you'll be given a sequence of operations to perform and should return the results of all get operations.

Input & Output

Example 1 — Basic Operations
$ Input: operations = [["put",1,1],["put",2,2],["get",1],["get",3],["put",2,1],["get",2],["remove",2],["get",2]]
Output: [1,-1,1,-1]
💡 Note: put(1,1), put(2,2), get(1)→1, get(3)→-1, put(2,1), get(2)→1, remove(2), get(2)→-1
Example 2 — Hash Collisions
$ Input: operations = [["put",17,70],["put",33,80],["get",17],["get",33]]
Output: [70,80]
💡 Note: Keys 17 and 33 hash to same bucket (17%16=1, 33%16=1), handled by chaining
Example 3 — Update Existing Key
$ Input: operations = [["put",1,10],["put",1,20],["get",1]]
Output: [20]
💡 Note: put(1,10) stores key 1, put(1,20) updates value to 20, get(1) returns 20

Constraints

  • 0 ≤ key, value ≤ 106
  • At most 104 calls to put, get, and remove

Visualization

Tap to expand
INPUTALGORITHMRESULTOperations to performHash table with chainingGet operation resultsOperations Array["put", 1, 1]["put", 17, 70]["get", 1]["get", 17]1Hash Functionkey % bucket_count2Collision HandlingLinked list chaining3Auto ResizeWhen load factor > 0.754Search ChainTraverse linked list in bucketBucket Array with Chains[0][1][2][3]Get Results[1, 70]get(1) → 1get(17) → 70Key Insight:Hash function distributes keys to buckets, chaining handles collisions,and automatic resizing maintains O(1) average performance as data grows.TutorialsPoint - Custom Hash Map | Resizing Hash Table with Load Factor Management
Asked in
Google 45 Amazon 38 Microsoft 32 Apple 28 Facebook 25
78.0K Views
High Frequency
~35 min Avg. Time
2.2K 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