Design an LRU cache
medium 85 minDesign an in-memory Least Recently Used cache with O(1) lookups, updates and evictions.
Watch lesson4:49
Implementation
Line by line, in four languages
The point: write it in this order: node, list, get, put, the rest. Each part is complete before the next begins, so you always have something that works.
| Part | Minutes | Why now |
|---|---|---|
| Node | 1 | Everything else talks about it |
| RecencyList | 6 | All pointer work, finished and checked |
| Create, get, peek | 4 | Shows that reading is using |
| put, evict | 6 | The three cases |
| remove, keys, check | 3 | What tests and layers need |
From the node to the cache
A record with two neighbours. It has no methods, because only the list may change the links.
class Node: __slots__ = ("key", "value", "prev", "next") def __init__(self, key=None, value=None): self.key = key # eviction starts at the node and must find the map entry self.value = value self.prev = None self.next = NoneLine 2
Four fields and nothing else. A cache has many nodes, so leaving out the dictionary of each object saves memory. It also turns a misspelled field into an error.
1 of 3
Why it is built this way
- No timestamp and no counter: the place in the list is the time.
- Sentinels are ordinary nodes without key and value, so one class is enough.
What differs, and why
| Language | Difference | Reason |
|---|---|---|
| Java | Needs java.util.*. Map.Entry for the evicted pair | Map.entry refuses nulls, so null values are refused too |
| C++ | The map owns nodes by unique_ptr, the list cannot be copied | A copied list would point at the sentinels of the first one |
| C++ | evict takes the pair out before erase | After erase the node and its key are gone |
| TypeScript | Map keeps insertion order, so a shorter version exists | Delete and set again moves a key to the end. Show the pointers first |
| Python | OrderedDict with move_to_end is the short version | It is a map and a doubly linked list inside |
C++
// The short C++ version: let std::list be the list, and keep iterators in the mapclass LruCache { struct Item { int key; int value; }; size_t capacity_; std::list<Item> order_; // front is most recent std::unordered_map<int, std::list<Item>::iterator> where_;public: explicit LruCache(size_t capacity) : capacity_(capacity) {} int get(int key) { auto it = where_.find(key); if (it == where_.end()) return -1; order_.splice(order_.begin(), order_, it->second); // moves the node, copies nothing return it->second->value; // the iterator is still valid } void put(int key, int value) { if (auto it = where_.find(key); it != where_.end()) { it->second->value = value; order_.splice(order_.begin(), order_, it->second); return; } if (order_.size() == capacity_) { where_.erase(order_.back().key); // the key is in the item, as always order_.pop_back(); } order_.push_front({key, value}); where_[key] = order_.begin(); }};splice re-points links and invalidates no iterator, so the iterators in the map stay good. Erase and push_front would allocate a new node and would need a new iterator in the map.