- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 94 lines of Python from the credited upstream file design-hashmap.py.
- The implementation visibly relies on hash lookup.
- No explicit loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4class ListNode(object):5 def __init__(self, key, val):6 self.val = val7 self.key = key8 self.next = None9 self.prev = None10 11 12class LinkedList(object):13 def __init__(self):14 self.head = None15 self.tail = None16 17 def insert(self, node):18 node.next, node.prev = None, None 19 if self.head is None:20 self.head = node21 else:22 self.tail.next = node23 node.prev = self.tail24 self.tail = node25 26 def delete(self, node):27 if node.prev:28 node.prev.next = node.next29 else:30 self.head = node.next31 if node.next:32 node.next.prev = node.prev33 else:34 self.tail = node.prev35 node.next, node.prev = None, None 36 37 def find(self, key):38 curr = self.head39 while curr:40 if curr.key == key:41 break42 curr = curr.next43 return curr44 45 46class MyHashMap(object):47 48 def __init__(self):49 """50 Initialize your data structure here.51 """52 self.__data = [LinkedList() for _ in xrange(10000)]53 54 def put(self, key, value):55 """56 value will always be positive.57 :type key: int58 :type value: int59 :rtype: void60 """61 l = self.__data[key % len(self.__data)]62 node = l.find(key)63 if node:64 node.val = value65 else:66 l.insert(ListNode(key, value))67 68 def get(self, key):69 """70 Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key71 :type key: int72 :rtype: int73 """74 l = self.__data[key % len(self.__data)]75 node = l.find(key)76 if node:77 return node.val78 else:79 return -180 81 def remove(self, key):82 """83 Removes the mapping of the specified value key if this map contains a mapping for the key84 :type key: int85 :rtype: void86 """87 l = self.__data[key % len(self.__data)]88 node = l.find(key)89 if node:90 l.delete(node)91 92 93 94