from collections import OrderedDict class LRUCache: def __init__(self, capacity: int): self.cache = OrderedDict() self.capacity = capacity def get(self, key: str) -> any: if key not in self.cache: return -1 # Move the accessed item to the end (most recently used) self.cache.move_to_end(key) return self.cache[key] def put(self, key: str, value: any) -> None: if key in self.cache: self.cache.move_to_end(key) self.cache[key] = value if len(self.cache) > self.capacity: # Remove the least recently used item (first item) self.cache.popitem(last=False) # Example usage lru_cache = LRUCache(2) lru_cache.put('apple', 1) lru_cache.put('banana', 2) print(lru_cache.get('apple')) # Returns 1, 'apple' becomes MRU lru_cache.put('cherry', 3) # Cache is full, 'banana' is removed print(lru_cache.get('banana')) # Returns -1 print(lru_cache.get('cherry')) # Returns 3