LRU Cache
Design a data structure for a Least Recently Used (LRU) cache that performs get and put in O(1) average time. Implement the Solution class:
Solution(capacity)creates a cache that holds at mostcapacitydistinct keys. The constructor is the first operation and does not count toward the call limit.get(key)returns the value stored forkey, or-1whenkeyis absent. A successfulgetmakeskeythe most recently used entry.put(key, value)storesvalueunderkeyand makeskeythe most recently used entry. Ifkeyis already present, update its value in place instead of adding a second entry. If the cache already holdscapacitydistinct keys, remove the least recently used key before inserting a new one.
Every operation is one method call on a single Solution instance. The reported output is null for the constructor and for every put, and the returned integer for every get.
Examples
Input: [["Solution","put","put","get"],[[2],[1,1],[2,2],[1]]]
Output: [null,null,null,1]
Input: [["Solution","put","get"],[[1],[2,1],[2]]]
Output: [null,null,1]
Hints
Combine a hash map from key to node with a doubly linked list ordered by recency. The map gives O(1) lookup by key and the list gives O(1) reordering.
Use dummy head and tail sentinels so that inserting at the front and removing the last node need no special cases for an empty list.
On `get`, and on `put` of an existing key, detach the node and reinsert it at the front. On `put` of a new key while the cache is full, delete the node just before the tail before inserting the new one.
Related Problems
LRU Cache
Design a data structure for a Least Recently Used (LRU) cache that performs `get` and `put` in O(1) average time. Implement the `Solution` class: