LRU Cache
MediumLinked List · Adobe
Design a data structure for a least recently used (LRU) cache with a fixed capacity.
Implement the class LRUCache:
LRUCache(capacity)creates an empty cache that can hold at mostcapacitykeys (capacityis positive).get(key)returns the value stored forkey, or-1ifkeyis not in the cache. A successfulgetcounts as a use ofkey.put(key, value)storesvalueunderkey, overwriting any existing value, and counts as a use ofkey. If adding a new key makes the cache hold more thancapacitykeys, first remove the least recently used key (the one whose lastgetorputis oldest). Updating an existing key never evicts anything.
Both get and put should run in O(1) average time.
In the examples, each line is a call and the output lists what each call returns (None for the constructor and put).
Example 1
- Input:
- LRUCache(2); put(5, 50); put(7, 70); get(5); put(9, 90); get(7); get(5); get(9)
- Output:
- [None,None,None,50,None,-1,50,90]
- Explanation
get(5)makes key 5 the most recently used, so whenput(9, 90)overflows the capacity of 2, key 7 is the one evicted.get(7)then returns -1.
Example 2
- Input:
- LRUCache(2); put(1, 10); put(2, 20); put(1, 15); put(3, 30); get(1); get(2)
- Output:
- [None,None,None,None,None,15,-1]
- Explanation
put(1, 15)overwrites key 1 and makes it most recent without growing the cache. Adding key 3 evicts key 2, the least recently used.
Example 3
- Input:
- LRUCache(1); put(4, 1); get(4); put(6, 2); get(4); get(6)
- Output:
- [None,None,1,None,-1,2]
- Explanation
- With room for one key, inserting key 6 evicts key 4.
Constraints
1 <= capacity <= 30000 <= key <= 10^40 <= value <= 10^5- At most
2 * 10^5calls will be made togetandput