LRU Cache
A cache of fixed size that throws out the key nobody has touched for longest - and does it in a constant number of steps.
Problem
Design a data structure that follows the Least Recently Used (LRU) policy. Implement LRUCache(capacity), get(key) which returns the value or -1, and put(key, value) which inserts or updates and evicts the least recently used key when over capacity.
- get and put must each take a constant number of steps, no matter how big the cache is.
- Reading a key with get counts as using it.
- Updating an existing key counts as using it.
Examples
Approach
- A map finds a key instantly but knows nothing about order. A doubly linked list - a chain where each node points both forwards and backwards - can move an item in one step but cannot find it. Use both together.
- The map stores key -> the node holding it. The chain runs from most recently used at the front to least recently used at the back. Two empty placeholder nodes sit at each end so you never have to special-case the first or last item.
- get: if the key is there, take its node out of the chain, put it back at the front, and return its value.
- put: update and move to front if the key exists; otherwise add a new node at the front, and if the size exceeds capacity, remove the node before the tail and delete its key from the map.
Brute force: Keep an array in recency order. Finding a key and moving it means walking the array each time.
Common mistakes
- Forgetting to move a key to the front on get, so reads do not count as use.
- Removing the list node but not the map entry, or the other way round.
- The node must store its key, or you cannot delete the evicted entry from the map.
Step through it
Pick an input and play the algorithm step by step. The highlighted line in the code follows each step, and you can edit the code to experiment.
Solution
The same approach in JavaScript, Python, and Java. Each is a complete program that prints the examples above - JavaScript runs here, so edit it and try your own input.
JavaScript solution
Output
Run code to see output...
Comments
Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.
Loading comments...
AI
System Design
Backend
- GraphQL8 modules · 69 lessons planned
- Core Python13 modules · 75 lessons planned
- FastAPI5 sections · 20 lessons
- Node.js14 modules · 206 lessons planned
- Node.js Performance7 chapters · 36 topics
- Event Loop Lifecycle6 phases · 3 scenarios
- Docker & Containerization11 modules · 144 lessons planned
- AWS for Developers14 modules · 219 lessons planned
- CI/CD & DevOps Automation10 modules · 134 lessons planned