Exact LRU needs to track recency on every access: with a hash map plus a doubly linked list (or an ordered dictionary) both get and put are O(1). In hardware, systems use approximations such as reference bits with the clock algorithm because exact tracking on every memory access is too costly.
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity):
self.cap = capacity
self.data = OrderedDict()
def get(self, key):
if key not in self.data:
return -1
self.data.move_to_end(key) # mark as most recently used
return self.data[key]
def put(self, key, value):
self.data[key] = value
self.data.move_to_end(key)
if len(self.data) > self.cap:
self.data.popitem(last=False) # evict least recently used