Leetcode 706. Design HashMap
Explanation for Leetcode 706 - Design HashMap, and its solution in Python.
Problem
Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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]]
Approach
We can use the same method that we used from Leetcode 705 - Design HashSet. Except that since we have to return a value, we’re going to initialize the array with -1.
Here is the Python code for the solution:
1
2
3
4
5
6
7
8
9
10
11
12
class MyHashMap:
def __init__(self):
self.arr = [-1] * 1000001
def put(self, key: int, value: int) -> None:
self.arr[key] = value
def get(self, key: int) -> int:
return self.arr[key]
def remove(self, key: int) -> None:
self.arr[key] = -1
Time Complexity and Space Complexity
Time Complexity: $O(1)$ since for each operation we’re just accessing array
Space Complexity: $O(10^6)$ since we’re storing the space of $10^6$
This post is licensed under CC BY 4.0 by the author.