- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 52 lines of Python from the credited upstream file 146.py.
- The implementation keeps its working state in language-native values and containers.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Node:2 def __init__(self, key: int, value: int):3 self.key = key4 self.value = value5 self.prev = None6 self.next = None7 8 9class LRUCache:10 def __init__(self, capacity: int):11 self.capacity = capacity12 self.keyToNode = {}13 self.head = Node(-1, -1)14 self.tail = Node(-1, -1)15 self.join(self.head, self.tail)16 17 def get(self, key: int) -> int:18 if key not in self.keyToNode:19 return -120 21 node = self.keyToNode[key]22 self.remove(node)23 self.moveToHead(node)24 return node.value25 26 def put(self, key: int, value: int) -> None:27 if key in self.keyToNode:28 node = self.keyToNode[key]29 node.value = value30 self.remove(node)31 self.moveToHead(node)32 return33 34 if len(self.keyToNode) == self.capacity:35 lastNode = self.tail.prev36 del self.keyToNode[lastNode.key]37 self.remove(lastNode)38 39 self.moveToHead(Node(key, value))40 self.keyToNode[key] = self.head.next41 42 def join(self, node1: Node, node2: Node):43 node1.next = node244 node2.prev = node145 46 def moveToHead(self, node: Node):47 self.join(node, self.head.next)48 self.join(self.head, node)49 50 def remove(self, node: Node):51 self.join(node.prev, node.next)52