Design and implement a Weighted LRU (Least Recently Used) Cache that extends the traditional LRU cache by assigning a size (or weight) to each item. Unlike a standard LRU cache where each item counts as 1 toward the capacity, in a weighted LRU cache, the capacity is calculated as the sum of all item sizes. This variant is commonly used in systems where cached items have varying memory footprints, such as:
Your implementation should support two core operations: [Source: darkinterview.com]
get(key): Retrieve the value associated with the key. Returns -1 if the key doesn't exist.put(key, value, size): Insert or update a key-value pair with an associated size. If adding the item causes the total size to exceed capacity, evict the least recently used items until there's enough space.`# Capacity is 10 (total weight, not item count) cache = WeightedLRUCache(capacity=10) cache.put("a", 1, 3) # Cache: {"a": (1, size=3)} -> total size = 3 cache.put("b", 2, 4) # Cache: {"a": (1, 3), "b": (2, 4)} -> total size = 7 cache.put("c", 3, 5) # Exceeds capacity (7 + 5 = 12 > 10) # Evict "a" (LRU, size=3) -> total size = 4 # Now add "c" -> total size = 9 # Cache: {"b": (2, 4), "c": (3, 5)} cache.get($L41) $L42 cache.get($L43) $L44 cache.put($L45, $L46, $L47) $L48