HashMap Implementation Lab
Easy
1
53.3% Acceptance
In this lab, you will be implementing a HashMap from scratch without using any built-in hash table libraries. Your main goal is to have a better understanding of how HashMaps work and practice creating your own data structure.
Problem Statement
Design a HashMap class with the following methods:
MyHashMap()
initializes the object with an empty map.void put(int key, int value)
inserts a(key, value)
pair into the HashMap. If thekey
already exists in the map, update the correspondingvalue
.int get(int key)
returns thevalue
to which the specifiedkey
is mapped, or-1
if this map contains no mapping for thekey
.void remove(key)
removes thekey
and its correspondingvalue
if the map contains the mapping for thekey
.
Example
const myHashMap = new MyHashMap(); myHashMap.put(1, 1); // The map is now [[1,1]] myHashMap.put(2, 2); // The map is now [[1,1], [2,2]] myHashMap.get(1); // Should return 1, The map is now [[1,1], [2,2]] myHashMap.get(3); // Should return -1 (i.e., not found), The map is now [[1,1], [2,2]] myHashMap.put(2, 1); // The map is now [[1,1], [2,1]] (i.e., updating the existing value) myHashMap.get(2); // Should return 1, The map is now [[1,1], [2,1]] myHashMap.remove(2); // Removing the mapping for 2, The map is now [[1,1]] myHashMap.get(2); // Should return -1 (i.e., not found), The map is now [[1,1]]
Constraints
0 <= key, value <= 10^6
- At most
10^4
calls will be made toput
,get
, andremove
.
Challenges
- Implement your
MyHashMap
class. - Make sure your
put
method properly updates the value if the key already exists. - Implement the
get
method to retrieve the value associated with a specific key. - Implement the
remove
method to remove a key and its associated value from the HashMap.