from collections import OrderedDict class LRUCache: def __init__(self, capacity: int): self.cache = OrderedDict() self.capacity = capacity def get(self, key: str) -> str: if key not in self.cache: return -1 # Or raise KeyError, depending on requirements # Move the accessed key to the end to mark it as most recently used value = self.cache.pop(key) self.cache[key] = value return value def put(self, key: str, value: str) -> None: if key in self.cache: self.cache.pop(key) # Remove existing entry to update order elif len(self.cache) >= self.capacity: self.cache.popitem(last=False) # Remove LRU item (first item) self.cache[key] = value # Add new item (or updated item) to the end # Example Usage lru_cache = LRUCache(3) lru_cache.put("key1", "value1") lru_cache.put("key2", "value2") lru_cache.put("key3", "value3") print(f"Cache after initial puts: {list(lru_cache.cache.items())}") lru_cache.get("key1") # Access key1, making it MRU print(f"Cache after getting key1: {list(lru_cache.cache.items())}") lru_cache.put("key4", "value4") # key2 should be evicted (LRU) print(f"Cache after putting key4: {list(lru_cache.cache.items())}") # Expected: [('key3', 'value3'), ('key1', 'value1'), ('key4', 'value4')]