Skip to content

Commit db31358

Browse files
committed
feat: implement set method with LRU eviction logic
- Add logic to update existing keys and move them to the front (MRU) - Implement eviction of the Least Recently Used (tail) node when the limit is reached - Ensure the lookup dictionary and linked list stay synchronized during eviction - Add new nodes to both the dictionary and the front of the list
1 parent e2d5a85 commit db31358

1 file changed

Lines changed: 25 additions & 0 deletions

File tree

‎Sprint-2/implement_lru_cache/lru_cache.py‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,3 +102,28 @@ def get(self, key):
102102
self.order.push_head(node)
103103

104104
return node.value
105+
106+
def set(self, key, value):
107+
"""
108+
Logic for set(key, value):
109+
If exists: update and move to front.
110+
If new: check limit, evict tail if full, then add to front.
111+
"""
112+
if key in self.lookup:
113+
# Update existing
114+
node = self.lookup[key]
115+
node.value = value
116+
self.order.remove(node)
117+
self.order.push_head(node)
118+
else:
119+
# Check limit
120+
if len(self.lookup) >= self.limit:
121+
# Evict the oldest (tail)
122+
evicted_node = self.order.pop_tail()
123+
if evicted_node:
124+
del self.lookup[evicted_node.key]
125+
126+
# Create and add new node
127+
new_node = Node(key, value)
128+
self.order.push_head(new_node)
129+
self.lookup[key] = new_node

0 commit comments

Comments
 (0)