Design HashMap

Try to solve the Design HashMap problem.

Statement

Design a HashMap data structure that supports the following operations:

  • Constructor(): Initializes the hash map object with an empty map to store the key-value pairs.

  • Put(key, value): Inserts a key-value pair into the hash map. If the specified key is already present in the hash map, the associated value is updated. Otherwise, the key-value pair is added to the hash map.

  • Get(key): Returns the value associated with the specified key if the key exists in the hash map. Otherwise, it returns 1-1, indicating the absence of a mapping for the key.

  • Remove(key): Removes the entry for the specified key from the hash map, effectively removing both the key and its associated value. This elimination only takes place when the key exists in the hash map.

Note: Your implementation should not utilize the built-in hash table libraries.

Constraints:

  • 00 \le key \le 10610^6
  • 00 \le value \le 10610^6
  • At most, 10410^4 calls can be made to the Put, Get, and Remove functions.

Examples

Press + to interact
canvasAnimation-image
1 of 7

Understand the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Design HashMap

1

What is the output of the following sequence of function calls on a hash map object?

Put(1, 500)
Put(2, 200)
Put(1, 150)
Get(1)
A)

500

B)

200

C)

150

D)

1

Question 1 of 30 attempted

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Drag and drop the cards to rearrange them in the correct sequence.

Try it yourself

Implement your solution in MyHashMap.cpp and Bucket.cpp in the following coding playground.

Press + to interact
C++
usercode > DesignHashMap.cpp
#include "Bucket.cpp"
class DesignHashMap {
public:
// Use the constructor below to initialize the
// hash map based on the keyspace
DesignHashMap() {
// Write your code here
}
void Put(int key, int value) {
// Write your code here
}
int Get(int key) {
// Replace this placeholder return statement with your code
return -1;
}
void Remove(int key) {
// Write your code here
}
};
Design HashMap