LRU Cache Implementation
Least Recently Used cache with O(1) get and put operations. Automatically evicts oldest items when capacity is exceeded.
Python7/16/2025
#data-structures#cache#algorithms
Python
class LRUCache:
def __init__(self, capacity):
self.capacity = capacity
self.cache = {}
self.order = []
def get(self, key):
if key in self.cache:
self.order.remove(key)
self.order.append(key)
return self.cache[key]
return None
def put(self, key, value):
if key in self.cache:
self.order.remove(key)
elif len(self.cache) >= self.capacity:
oldest = self.order.pop(0)
del self.cache[oldest]
self.cache[key] = value
self.order.append(key)...
Loading comments...