LRU Cache
MediumLinked List
Decode it first. Clues, constraints, pattern and plan before any code.Design a class LRUCache that holds at most capacity key-value pairs and, when it is full, throws out the least recently used key.
LRUCache(capacity)creates an empty cache.get(key)returns the value forkey, or-1if it is not there. A successfulgetcounts as using the key.put(key, value)inserts or updates the key, which also counts as using it. If this adds a new key and the cache is already full, first remove the key that was used longest ago.
Both get and put must run in O(1) average time.
cache = LRUCache(2)
put(1, 1); put(2, 2)
get(1) → 1 (1 is now the most recent)
put(3, 3) (full: evicts 2, the least recent)
get(2) → -1
put(4, 4) (evicts 1)
get(1) → -1
get(3) → 3
get(4) → 4Constraints
1 <= capacity <= 30000 <= key <= 10^40 <= value <= 10^5- At most
2 * 10^5calls togetandput.