design-hashmap py3

This commit is contained in:
Sangeeth Sudheer 2022-04-23 18:32:42 +05:30
parent 0a81a963ae
commit a0b3f7f134
2 changed files with 94 additions and 0 deletions

View File

@ -0,0 +1,33 @@
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`.

View File

@ -0,0 +1,61 @@
# Time: O(N / K) ; N is num of all keys and K is num of predefined buckets
# Space: O(K + M) ; K is num of predefined buckets and M is no. of unique
# keys inserted
from collections import deque
class MyHashMap:
def __init__(self):
# TODO: Better hash function and better initial capacity needed
# Maybe initial capacity can even be passed as an option?
self.store = [Bucket()] * 997
def put(self, key: int, value: int) -> None:
i = self._hash(key)
self.store[i].upsert(key, value)
def get(self, key: int) -> int:
i = self._hash(key)
pair = self.store[i].get_pair(key)
return pair[1] if pair else -1
def remove(self, key: int) -> None:
i = self._hash(key)
return self.store[i].remove(key)
def _hash(self, key: int):
# TODO: Note down better hash functions
return key % 997
class Bucket:
def __init__(self):
self.d = deque()
def upsert(self, key, value):
pair = self.get_pair(key)
if pair is not None:
pair[1] = value
else:
self.d.append([key, value])
def get_pair(self, key):
for item in self.d:
if item[0] == key:
return item
def remove(self, key):
item = self.get_pair(key)
if item is not None:
self.d.remove(item)
# Your MyHashMap object will be instantiated and called as such:
# obj = MyHashMap()
# obj.put(key,value)
# param_2 = obj.get(key)
# obj.remove(key)