Cache that evicts the least-used key
Write a class LFUCache that stores at most capacity key-value pairs and follows the least-frequently-used (LFU) policy.
get(key)returns the value stored forkey, or-1if the key is absent.put(key, value)stores the pair, overwriting any old value. Ifkeyis new and the cache is already full, it first evicts the key with the fewest uses; among keys tied on uses, the one that has gone longest without a use goes.
Each key counts its uses while it is stored: a put, and a get that finds the key, each add one, so a new key starts at 1. Both operations must be O(1) on average. Keys and values are non-negative integers and capacity >= 1.
The tests call the provided run_cache(capacity, ops): it builds the cache, applies each operation in order and returns the list of results (None for put, shown as null).
Besides the tests, one large input (3,000 keys, 2,000 evictions) with a ~350 ms limit (scaled to your device's speed): brute force won't pass.
Examples
run_cache(2, [["put",1,10],["put",2,20],["get",1],["put",3,30],["get",2],["get",3],["get",1]])→[null,null,10,null,-1,30,10]run_cache(2, [["put",1,1],["put",2,2],["get",1],["get",2],["put",3,3],["get",1],["get",2],["get",3]])→[null,null,1,2,null,-1,2,3]run_cache(2, [["put",5,50],["put",6,60],["get",5],["get",5],["get",6],["put",7,70],["get",5],["get",6],["get",7]])→[null,null,50,50,60,null,50,-1,70]