From a93bb068b66d0b7f668254071f59bb4fd90c2079 Mon Sep 17 00:00:00 2001 From: Prad Nukala Date: Tue, 1 Sep 2026 13:59:03 -0400 Subject: [PATCH] fix(work): correct node insertion and eviction order in LRUCache --- work/1/Medium/Hash Table/146.lru-cache.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/work/1/Medium/Hash Table/146.lru-cache.py b/work/1/Medium/Hash Table/146.lru-cache.py index 3b02b3b..0951098 100644 --- a/work/1/Medium/Hash Table/146.lru-cache.py +++ b/work/1/Medium/Hash Table/146.lru-cache.py @@ -87,10 +87,11 @@ class LRUCache: next_node.prev = prev_node def _add_node(self, node): - node.prev = self.head - node.next = self.head.next - self.head.next.prev = node # pyright: ignore[reportAttributeAccessIssue] - self.head.next = node + # Insert just before the tail (most recent at end) + node.next = self.tail + node.prev = self.tail.prev + self.tail.prev.next = node # pyright: ignore[reportAttributeAccessIssue] + self.tail.prev = node def get(self, key: int) -> int: if key not in self.cache: @@ -113,7 +114,7 @@ class LRUCache: self._add_node(new_node) 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) del self.cache[lru.key] # pyright: ignore[reportAttributeAccessIssue]