Design HashMap

Build your own hash map from integer keys to integer values. Do not use the built-in Map, Set or plain objects as the map itself; arrays are fine.

Implement the class MyHashMap:

  • new MyHashMap() creates an empty map.
  • put(key, value) stores the pair. If the key is already present, replace its value.
  • get(key) returns the value stored for key, or -1 if the key is not in the map.
  • remove(key) removes the key and its value if present, and does nothing otherwise.

Each test is a sequence of calls. The first call creates the object. Calls that return nothing are shown as null in the expected output, and their return value isn't checked.

Constraints

  • 0 <= key, value <= 10^6
  • At most 10^4 calls in total.

Examples

Example 1

Input: ["MyHashMap","put","put","get","get","put","get","remove","get"]
       [[],[1,1],[2,2],[1],[3],[2,1],[2],[2],[2]]
Output: [null,null,null,1,-1,null,1,null,-1]

get(3) was never stored, so -1. put(2, 1) replaces the earlier value 2, and after remove(2) the key is gone again.

Example 2

Input: ["MyHashMap","get","put","get","remove","get"]
       [[],[0],[0,0],[0],[0],[0]]
Output: [null,-1,null,0,null,-1]

A stored value of 0 is different from a missing key, which answers -1.

Example 3

Input: ["MyHashMap","put","put","put","get","get","get","remove","get","get","get"]
       [[],[1,10],[1001,20],[2001,30],[1],[1001],[2001],[1001],[1],[1001],[2001]]
Output: [null,null,null,null,10,20,30,null,10,-1,30]

Keys 1, 1001 and 2001 share a bucket when there are 1000 buckets. Removing one must leave the others.

Each test creates the class with the first operation, then calls the methods in order. Output lists what each call returns; null marks the constructor and methods that return nothing, and their return values aren't checked.

JavaScript you'll use: Classes for data structures Arrays: create, read, update

class MyHashMap {
  constructor() {
    
  }

  /**
   * Stores the pair, replacing the value if the key is already present.
   * @param {number} key
   * @param {number} value
   * @return {void}
   */
  put(key, value) {
    
  }

  /**
   * @param {number} key
   * @return {number} the value stored for the key, or -1 if the key is absent
   */
  get(key) {
    
  }

  /**
   * Removes the key if it is present.
   * @param {number} key
   * @return {void}
   */
  remove(key) {
    
  }
}

Ctrl/⌘ + ' runs the examples, Ctrl/⌘ + Enter submits. Use console.log freely: output shows under Console. In the editor, press Esc then Tab to move focus out.