Taro Logo

Design HashMap

#3 Most AskedEasy
0 views
Topics:
ArraysLinked ListsDynamic Programming

Design a HashMap without using any built-in hash table libraries.

Implement the MyHashMap class:

  • 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 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]

Explanation
MyHashMap 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);    // return 1, The map is now [[1,1], [2,2]]
myHashMap.get(3);    // 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., update the existing value)
myHashMap.get(2);    // return 1, The map is now [[1,1], [2,1]]
myHashMap.remove(2); // remove the mapping for 2, The map is now [[1,1]]
myHashMap.get(2);    // return -1 (i.e., not found), The map is now [[1,1]]

Constraints:

  • 0 <= key, value <= 106
  • At most 104 calls will be made to put, get, and remove.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What are the data types and value ranges for the keys and values we will be storing (e.g., are they exclusively non-negative integers)?
  2. What should `get` return if the requested key does not exist in the HashMap?
  3. How should we handle collisions when two different keys hash to the same index?
  4. What is the expected capacity or maximum number of key-value pairs we need to support, and should the map dynamically resize?
  5. Can we assume that `null` or invalid pointers won't be passed as keys or values, or do we need to handle those explicitly?

Brute Force Solution

Approach

Imagine you have a giant blank notebook where you need to remember pairs of things, like a person's name and their phone number. The simplest and most straightforward way to handle this is to just write every single pair down on a long list of paper one after the other.

Here's how the algorithm would work step-by-step:

  1. Start with a completely blank notebook page.
  2. Whenever someone asks you to remember a new pair of information, flip to the very end of your written list and write it down as a brand new entry.
  3. Whenever someone asks you to look up a piece of information, start at the very top of your list and read down every single line until you spot the matching name.
  4. If you find the name, look right next to it to read the corresponding phone number you wrote down earlier.
  5. Whenever someone asks you to delete a piece of information, read down the list until you find the correct name, and then cross that entire line out so you never look at it again.

Code Implementation

class MyHashMap:
    def __init__(self):
        self.entry_storage_list = []

    def put(self, key: int, value: int) -> None:
        # We iterate to update existing keys instead of duplicating, ensuring uniqueness per key
        for entry_index, stored_pair in enumerate(self.entry_storage_list):
            if stored_pair[0] == key:
                self.entry_storage_list[entry_index] = (key, value)
                return
        self.entry_storage_list.append((key, value))

    def get(self, key: int) -> int:
        # Linear scan is required to check every element sequentially since keys are unordered
        for stored_pair in self.entry_storage_list:
            if stored_pair[0] == key:
                return stored_pair[1]
        return -1

    def remove(self, key: int) -> None:
        # We iterate backward or filter to safely remove the target key without index shifting bugs
        for entry_index, stored_pair in enumerate(self.entry_storage_list):
            if stored_pair[0] == key:
                del self.entry_storage_list[entry_index]
                return

Big(O) Analysis

Time Complexity
O(n) – For every operation like put, get, or remove, we must potentially check every single element currently stored in our list of n pairs. In the worst-case scenario, the target key is at the very end of the list or not present at all, requiring us to inspect all n entries sequentially. This means the total operations scale linearly with n, which simplifies to O(n).
Space Complexity
O(N) – The auxiliary space is driven by the long list of paper described in the steps, which stores every key-value pair sequentially. As new pairs are added, this linear list grows directly proportional to the total number of entries, N. Therefore, the extra memory required scales linearly with the number of inserted elements.

Optimal Solution

Approach

Instead of keeping everything in one long, unorganized list, the optimal approach divides items into several labeled filing cabinets based on their unique identification numbers. This way, when you need to find, add, or remove something, you only have to look through a tiny fraction of the total items rather than searching through everything.

Here's how the algorithm would work step-by-step:

  1. Set up a row of designated holding spots, each meant to catch specific identification numbers using a simple matching rule.
  2. When you are given a pair of items to store, pass the identification number through the matching rule to find out which holding spot it belongs to.
  3. Check inside that specific holding spot to see if the identification number is already present.
  4. If the identification number is already there, simply update its associated value with the new information.
  5. If the identification number is not there yet, create a new entry inside that holding spot and place the pair neatly at the end of the group.
  6. When asked to retrieve a value, send the identification number through the matching rule again to go straight to the correct holding spot.
  7. Look through that specific holding spot to find the matching identification number and hand back its associated value, or report that it is missing if it was never stored.

Code Implementation

class MyHashMap:
    def __init__(self):
        self.bucket_count = 2069
        self.bucket_array = [[] for _ in range(self.bucket_count)]

    def _hash_function(self, target_key):
        return target_key % self.bucket_count

    def put(self, target_key: int, target_value: int) -> None:
        bucket_index = self._hash_function(target_key)
        target_bucket = self.bucket_array[bucket_index]

        # We iterate through the bucket to check if the key already exists to prevent duplicates.
        for index, pair in enumerate(target_bucket):
            if pair[0] == target_key:
                target_bucket[index] = (target_key, target_value)
                return

        target_bucket.append((target_key, target_value))

    def get(self, target_key: int) -> int:
        bucket_index = self._hash_function(target_key)
        target_bucket = self.bucket_array[bucket_index]

        # We search specifically within the assigned bucket to ensure fast retrieval times.
        for pair in target_bucket:
            if pair[0] == target_key:
                return pair[1]

        return -1

    def remove(self, target_key: int) -> None:
        bucket_index = self._hash_function(target_key)
        target_bucket = self.bucket_array[bucket_index]

        # We check every stored pair in the bucket to isolate and safely delete the target key.
        for index, pair in enumerate(target_bucket):
            if pair[0] == target_key:
                target_bucket.pop(index)
                return

Big(O) Analysis

Time Complexity
O(n/k) – For n total stored items distributed across k holding spots, sending the identification number through the matching rule gives direct access to a specific spot containing approximately n/k items. Looking through that particular holding spot requires sequentially checking the entries stored inside it. In the worst case where many items land in the same spot, this scan takes proportional to n operations. Assuming a well-distributed hash map where k scales with n, the average time complexity simplifies to O(1).
Space Complexity
O(N + K) – The auxiliary space is driven by the row of designated holding spots of size K and the stored key-value pairs distributed across them, where N is the total number of unique keys inserted and K is the fixed number of buckets. As N grows, the additional memory required scales linearly to store all the entry nodes within these holding spots. Therefore, the total extra memory simplifies to Big O notation of O(N + K).

Edge Cases

Key already exists during an insert operation
How to Handle:
The update operation overwrites the existing value associated with that key instead of creating a duplicate entry.
Key does not exist during a get or remove operation
How to Handle:
The lookup returns negative one or gracefully skips deletion if the key is absent from the bucket.
Negative keys or zero as a key
How to Handle:
The hash function applies an absolute value or modulo operation properly to map negative integers to valid bucket indices.
Maximum possible integer values for keys
How to Handle:
The hash function uses safe arithmetic or bitwise operations to prevent integer overflow during index calculation.
High collision rate due to poorly distributed keys
How to Handle:
Each bucket uses a linked list or secondary data structure to handle multiple entries mapping to the same index.
Removing the only element in a bucket
How to Handle:
The bucket head pointer is updated directly to null or the next node to maintain correct list integrity.
Removing the head node of a bucket's linked list
How to Handle:
A dummy or sentinel node at the start of each bucket simplifies pointer manipulation during deletion.
Exceeding initial capacity with a massive number of insertions
How to Handle:
The map should use a sufficiently large fixed array size or implement dynamic resizing to maintain average constant time complexity.
0/6 completed