HashMap Implementation Lab

Easy
2
36.7% 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 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(key) removes the key and its corresponding value if the map contains the mapping for the key.

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 to put, get, and remove.

Challenges

  1. Implement your MyHashMap class.
  2. Make sure your put method properly updates the value if the key already exists.
  3. Implement the get method to retrieve the value associated with a specific key.
  4. Implement the remove method to remove a key and its associated value from the HashMap.