#706
Design HashMap
EasyArrayHash TableLinked ListDesignHash FunctionHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(1) average case |
| Space | O(1) | O(n) |
💡
Intuition
Time O(1) average caseSpace O(n)
An optimal solution uses a hash table with an array of linked lists (or buckets) to store key-value pairs. This allows for efficient insertion, retrieval, and deletion operations by minimizing collisions.
⚙️
Algorithm
5 steps- 1Step 1: Initialize an array of linked lists to store key-value pairs.
- 2Step 2: Use a hash function to compute the index for the key.
- 3Step 3: For 'put', check if the key exists in the linked list at the computed index; if it does, update the value; if not, add a new node.
- 4Step 4: For 'get', compute the index and search the linked list for the key, returning the corresponding value or -1 if not found.
- 5Step 5: For 'remove', compute the index and search the linked list to find and remove the node with the key.
solution.py51 lines
1class ListNode:
2 def __init__(self, key, value):
3 self.key = key
4 self.value = value
5 self.next = None
6
7class MyHashMap:
8 def __init__(self):
9 self.size = 1000
10 self.map = [None] * self.size
11
12 def _hash(self, key):
13 return key % self.size
14
15 def put(self, key: int, value: int) -> None:
16 index = self._hash(key)
17 if not self.map[index]:
18 self.map[index] = ListNode(-1, -1)
19 prev = self.map[index]
20 curr = prev.next
21 while curr:
22 if curr.key == key:
23 curr.value = value
24 return
25 prev = curr
26 curr = curr.next
27 prev.next = ListNode(key, value)
28
29 def get(self, key: int) -> int:
30 index = self._hash(key)
31 if not self.map[index]:
32 return -1
33 curr = self.map[index].next
34 while curr:
35 if curr.key == key:
36 return curr.value
37 curr = curr.next
38 return -1
39
40 def remove(self, key: int) -> None:
41 index = self._hash(key)
42 if not self.map[index]:
43 return
44 prev = self.map[index]
45 curr = prev.next
46 while curr:
47 if curr.key == key:
48 prev.next = curr.next
49 return
50 prev = curr
51 curr = curr.nextℹ
Complexity note: The average time complexity for put, get, and remove operations is O(1) due to the efficient use of hash functions and linked lists to handle collisions. However, in the worst case (if many keys hash to the same index), it can degrade to O(n).
- 1Understanding hash functions is crucial to efficiently mapping keys to indices.
- 2Handling collisions properly is essential for maintaining performance.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.