fix(work): correct node insertion and eviction order in LRUCache

This commit is contained in:
Prad Nukala
2026-09-01 13:59:03 -04:00
parent 53b2d5ec8c
commit a93bb068b6
+6 -5
View File
@@ -87,10 +87,11 @@ class LRUCache:
next_node.prev = prev_node next_node.prev = prev_node
def _add_node(self, node): def _add_node(self, node):
node.prev = self.head # Insert just before the tail (most recent at end)
node.next = self.head.next node.next = self.tail
self.head.next.prev = node # pyright: ignore[reportAttributeAccessIssue] node.prev = self.tail.prev
self.head.next = node self.tail.prev.next = node # pyright: ignore[reportAttributeAccessIssue]
self.tail.prev = node
def get(self, key: int) -> int: def get(self, key: int) -> int:
if key not in self.cache: if key not in self.cache:
@@ -113,7 +114,7 @@ class LRUCache:
self._add_node(new_node) self._add_node(new_node)
if len(self.cache) > self.capacity: if len(self.cache) > self.capacity:
lru = self.tail.prev lru = self.head.next # Oldest node is next to the head
self._remove_node(lru) self._remove_node(lru)
del self.cache[lru.key] # pyright: ignore[reportAttributeAccessIssue] del self.cache[lru.key] # pyright: ignore[reportAttributeAccessIssue]