LRU Cache
Medium
Topics
Design an LRU (Least Recently Used) cache with get(key) and put(key, value), both O(1). The constructor takes a positive capacity. get returns the value or -1; put inserts/updates and evicts the least recently used key when over capacity.
Example 1
A cache with a fixed capacity. Reading a key counts as using it, so a
get moves that key out of danger; when a put would overflow the capacity, the key that has gone longest without use is the one dropped. A get on a key that is absent or already evicted answers -1.Calls run top to bottom; the arrow shows what each one returns.
Input: operations = ["LRUCache","put","put","get","put","get","put","get","get","get"], values = [[2],[1,1],[2,2],[1],[3,3],[2],[4,4],[1],[3],[4]] Output: [null,null,null,1,null,-1,null,-1,3,4]
Constraints
- 1 <= capacity <= 3000
- 0 <= key, value <= 10^4
- At most 2*10^5 calls.
Editorial — intuition, approach, complexity and pitfalls
Intuition
You need O(1) lookup and O(1) recency updates. A hash map gives lookup; a doubly-linked list (or an ordered map) gives O(1) move-to-most-recent and eviction of the tail.
Approach
- Maintain a hash map from key to node and a doubly-linked list ordered by recency.
- On get/put, move the touched key to the most-recent end.
- On overflow, evict the least-recent (front) key.
Dry Run
LRUCache(2). The OrderedDict is kept oldest-first, so the least recently used
item is always at the front and `popitem(last=False)` evicts it.
put 1 1 -> null order [(1,1)]
put 2 2 -> null order [(1,1), (2,2)]
get 1 -> 1 order [(2,2), (1,1)] -- the read MOVED 1 to the back
put 3 3 -> null order [(1,1), (3,3)] -- over capacity, 2 evicted
get 2 -> -1 2 is gone
put 4 4 -> null order [(3,3), (4,4)] -- 1 evicted
get 1 -> -1
get 3 -> 3 order [(4,4), (3,3)]
get 4 -> 4 order [(3,3), (4,4)]
answer null|null|null|1|null|-1|null|-1|3|4
The `get 1` row is the one that decides the whole sequence. A read is a USE, so it
refreshes recency, and that is why 2 is the victim at `put 3 3` rather than 1.
Drop `move_to_end` from get and 1 stays the oldest entry, so put 3 evicts it
instead -- the run then returns 2 at `get 2` where the answer is -1.
Eviction is checked after insertion, not before, which is why the dictionary is
briefly allowed to hold capacity + 1 entries. That ordering matters when the key
already exists: `put` on a present key must not evict anything, and here it
cannot, because the length does not grow.
Note put also refreshes recency for an existing key, via the same move_to_end.
Overwriting a value is a use too.Complexity
- Time — O(1): hash map + linked list give constant-time operations.
- Space — O(capacity): stored entries.
Common Pitfalls
- Update recency on get too, not just put.
Full Solution — all languages
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity):
self.cap = capacity
self.cache = OrderedDict()
def get(self, key):
if key not in self.cache:
return -1
self.cache.move_to_end(key)
return self.cache[key]
def put(self, key, value):
if key in self.cache:
self.cache.move_to_end(key)
self.cache[key] = value
if len(self.cache) > self.cap:
self.cache.popitem(last=False)import java.util.*;
class LRUCache {
int cap;
LinkedHashMap<Integer, Integer> map = new LinkedHashMap<>();
public LRUCache(int capacity) {
cap = capacity;
}
public int get(int key) {
if (!map.containsKey(key)) return -1;
int v = map.remove(key);
map.put(key, v);
return v;
}
public void put(int key, int value) {
if (map.containsKey(key)) map.remove(key);
map.put(key, value);
if (map.size() > cap) map.remove(map.keySet().iterator().next());
}
}#include <bits/stdc++.h>
using namespace std;
class LRUCache {
int cap;
list<pair<int,int>> lru;
unordered_map<int, list<pair<int,int>>::iterator> mp;
public: LRUCache(int capacity) : cap(capacity) {
}
int get(int key) {
if (!mp.count(key)) return -1;
lru.splice(lru.begin(), lru, mp[key]);
return mp[key]->second;
}
void put(int key, int value) {
if (mp.count(key)) {
mp[key]->second = value;
lru.splice(lru.begin(), lru, mp[key]);
return;
}
if ((int)lru.size() >= cap) {
mp.erase(lru.back().first);
lru.pop_back();
}
lru.push_front({key, value});
mp[key] = lru.begin();
}
};class LRUCache {
constructor(capacity) {
this.cap = capacity;
this.map = new Map();
}
get(key) {
if (!this.map.has(key)) return -1;
const v = this.map.get(key);
this.map.delete(key);
this.map.set(key, v);
return v;
}
put(key, value) {
if (this.map.has(key)) this.map.delete(key);
this.map.set(key, value);
if (this.map.size > this.cap) this.map.delete(this.map.keys().next().value);
}
}