November 26, 2024
This took me a few days although it's only a medium! It is important to remember Python is pass-by-reference. I spent a lot of time debugging because I didn't mirror changes between previous and next nodes when moving a node between them. I was able to debug by creating a list of key-value pairs then printing the list after each operation.
1class Node:2 def __init__(self, key=0, val=0, prev=None, next=None):3 self.key = key4 self.val = val5 self.prev = prev6 self.next = next78class LRUCache:9 def __init__(self, capacity: int):10 self.capacity = capacity11 self.size = 012 self.d = {}13 self.l = None14 self.start = None1516 def get(self, key: int) -> int:17 if key in self.d:18 node = self.d[key]19 if node.prev and node.next:20 node.prev.next = node.next21 node.next.prev = node.prev22 elif node.next:23 self.start = node.next24 self.start.prev = None25 if self.l != node:26 node.prev = self.l27 self.l.next = node28 self.l = self.l.next29 self.l.next = None30 return node.val31 else:32 return -13334 def put(self, key: int, value: int) -> None:35 if not key in self.d:36 if self.size == self.capacity:37 node = self.start38 del self.d[node.key]39 self.start = node.next40 if self.start:41 self.start.prev = None42 self.size -= 143 if self.l:44 self.l.next = Node(key, value, self.l)45 self.l = self.l.next46 if not self.start:47 self.start = Node(key, value)48 self.l = self.start49 self.d[key] = self.l50 self.size += 151 else:52 node = self.d[key]53 if node == self.start and self.start.next:54 self.start = self.start.next55 self.start.prev = None56 if node.prev and node.next:57 node.prev.next = node.next58 node.next.prev = node.prev59 if node != self.l:60 node.prev = self.l61 self.l.next = node62 node.val = value63 node.next = None64 self.l = node65666768# Your LRUCache object will be instantiated and called as such:69# obj = LRUCache(capacity)70# param_1 = obj.get(key)71# obj.put(key,value)
Time complexity for get and put operations are O(n) = 1 and space complexity is O(n) due to the dictionary holding each element.
LeetCode 86. Partition List
LeetCode 105. Construct Binary Tree from Preoder and Inorder Traversal