Design HashMap LeetCode Interview Question (Explained Simply)

Hash maps are used to store data in key-value pairs.

They are similar to arrays because arrays values are stored against numeric keys known as indexes.

Hash maps allow us to have flexible keys.

The upside to hash maps is that they have lighting fast searches and insertions. The downside is they can be memory hogs when you insert the same thing over and over (ex. inserting multiple zeros for multiple keys). Lastly, they can be incredibly slow when iterating over large datasets.

Design a hash map without using any built-in hash table libraries (and name it “MyHashMap”)

  • MyHashMap() initializes the object with an empty map.
  • put(key, value) inserts a pair into the HashMap. If the key already exists in the map, update the corresponding value
  • get(key, value) returns the value to which the specified key is mapped, or -1 if this map contains no mapping,
  • remove(key) removes the key and it’s corresponding value if the map contains the mapping for the key.

Step-By-Step

  • Before creating the actual hash map, an array must be create to hold the data
  • We then define the Put function, which accesses the array we made by a key/value pair and places the value into the key in memory.
  • We then define the Get function, which accesses the value via bracket notation
  • We then define the Remove function, which behaves very similar to the Put function but places a -1 in memory instead of the value.
public class MyHashMap {
   
    int[] arr;

    public MyHashMap() {
    
        arr=new int [1000];
        Array.Fill(a, -1);

    }

    public void Put(int key, int value) {
        a[key]=value;
    }

    public int Get(int key) {
        return a[key];
    }

    public void Remove(int key) {
        a[key]=-1;
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *