from collections import OrderedDict class LRUCache: def __init__(self, capacity: int): self.cache = OrderedDict() # Stores key-value pairs self.capacity = capacity # Maximum number of items in cache def get(self, key: str) -> str or None: if key not in self.cache: return None # Move the accessed item to the end (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 item to update its position elif len(self.cache) >= self.capacity: # If cache is full, remove the least recently used item (first item) self.cache.popitem(last=False) self.cache[key] = value # Add or update item at the end (most recently used) def __repr__(self): return str(self.cache) # Example Usage: cache = LRUCache(capacity=3) cache.put("A", "Value A") cache.put("B", "Value B") cache.put("C", "Value C") print(f"Cache state 1: {cache}") cache.get("B") # Access B, making it most recently used print(f"Cache state 2 (accessed B): {cache}") cache.put("D", "Value D") # Add D, C should be removed as it's least recently used print(f"Cache state 3 (added D): {cache}") print(f"Getting A: {cache.get('A')}") # A should exist print(f"Getting C: {cache.get('C')}") # C should be None print(f"Cache state 4 (accessed A): {cache}")