Weighted Eviction Cache
NetflixPhone screenMedium
Design a cache that stores integer entries under a total weight limit. Every entry has a key, a value and a weight of at least 1, and the total weight of all stored entries may never exceed the capacity. Whenever the total weight is above the capacity, the cache evicts the entry with the largest weight, breaking ties by the smaller key, and repeats until the total fits. Reading an entry does not change which entry is evicted next.
Each test drives one WeightedCache instance through a sequence of calls and checks every return value.
Part 1: Evict the heaviest
Implement a weighted cache with a fixed capacity.
put(key, value, weight): ifweightis greater thancapacity, do nothing at all, even whenkeyalready exists. Otherwise store the entry, replacing any earlier entry underkeytogether with its weight, then evict while the total weight of all entries exceedscapacity: each eviction removes the entry with the largest weight, breaking ties by the smaller key. The new entry can itself be evicted. Returns nothing.get(key): returns the stored value, or-1ifkeyis not stored.
Reading an entry never changes which entry is evicted next.
- Example 1
- init
[10]- operations
[["put",[1,100,4]],["put",[2,200,5]],["get",[1]],["get",[2]],["put",[3,300,3]],["get",[1]],["get",[2]],["get",[3]],["get",[9]]]- Output
[null,null,100,200,null,100,-1,300,-1]
Why: Entries 1 (weight 4) and 2 (weight 5) fit in 10. Adding 3 (weight 3) makes the total 12, so the heaviest entry, key 2, is evicted and the total drops to 7.
Constraints
1 <= len(operations) <= 10^41 <= capacity <= 10^91 <= weight <= 10^90 <= key <= 10^90 <= value <= 10^9