What is LRU Cache
Design a cache of fixed capacity. GET key returns the stored value, or -1 when the key is absent. PUT key value inserts or updates a key. When the cache is full, the least recently used key is removed before the new key is stored. Every successful get or put makes that key the most recent one.
Example. Capacity 2. Put 1 and 2, get 1, put 3. Key 2 is the least recent, so it leaves. Get 2 returns -1 and get 3 returns 3.
PUT 1 1, PUT 2 2, GET 1, PUT 3 3, GET 2, GET 3 Output: 1 -1 3
Constraints. 1 ≤ capacity ≤ 3000, 1 ≤ operations ≤ 104. This picture keeps capacity at 4 and draws 8 operations.
Approach
Interactive solution
The finished structure is on screen when the page opens. Next and Play start again from the first step.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Get | O(1) | The map finds the key and the order moves it to the recent end. |
| Put | O(1) | Update, insert, and eviction each touch one end of the order. |
Implementation
def get(self, key):
if key not in self.cache:
return -1
value = self.cache.pop(key)
self.cache[key] = value
return value
def put(self, key, value):
if key in self.cache:
self.cache.pop(key)
elif len(self.cache) >= self.capacity:
oldest = next(iter(self.cache))
self.cache.pop(oldest)
self.cache[key] = value