LRU Cache
MediumNeetCode 150Top Interview 150 Linked ListAppleTikTokNutanixNvidiaAmazonMetaProblem
Build a class LRUCache, a small cache that forgets the entry used least recently when it
runs out of room. It has these operations:
LRUCache(capacity)creates an empty cache that holds at mostcapacityentries.get(key)returns the value stored forkey, or-1if there is none. A successfulgetcounts as using that key.put(key, value)stores the pair, replacing the old value if the key exists. Storing a key counts as using it. If that makes the cache hold more thancapacityentries, the least recently used one is removed.
get and put must both run in O(1) average time. The input is the list of calls and their
arguments; the output lists what each call returns (null for the constructor and for put).
Constraints
- 1 ≤ capacity ≤ 3000
- 0 ≤ key ≤ 10⁴, 0 ≤ value ≤ 10⁵
- At most 2 · 10⁵ calls in total
Examples: pick one to animate
Solutions
Time: The map finds a node in constant time, and unlinking or inserting a node in a doubly linked list rewires a fixed number of pointers.
Space: At most capacity entries are stored, each as one map entry and one list node, plus the two sentinels.
The list keeps entries in order of use: the node after the head is the least recent, the node before the tail the most recent. A hash map from key to node gives instant access, and a node can be unlinked from the middle because it knows both of its neighbours. Every use moves the node to the tail end; eviction removes the node after the head.