Lesson 83 of 296
LRU cache
On this page
The task
"Design an LRU cache with a fixed capacity. get(key) returns the value or -1. put(key, value) adds or updates a value. When the cache is full, remove the least recently used item. Both operations must be O(1)."
This is LeetCode problem 146 and one of the most common interview questions for both front end and back end roles.
What LRU means
A cache has limited space. When it is full and a new item arrives, something must be removed. LRU (Least Recently Used) removes the item that has not been read or written for the longest time. The idea: recently used things are likely to be used again soon.
Capacity 2:
put(1, "A") cache: 1
put(2, "B") cache: 1, 2 (2 is most recent)
get(1) cache: 2, 1 (1 is now most recent)
put(3, "C") full: remove the least recently used, which is 2
cache: 1, 3
get(2) -1What the interviewer is checking
- That you know O(1) means "same time no matter how big the cache is".
- Which data structures give O(1) lookups and O(1) ordering updates.
Questions to ask first
- "Does
getcount as a use?" (Yes, in standard LRU.) - "Does updating an existing key with
putcount as a use?" (Yes.) - "What is the minimum capacity?"
The JavaScript trick: Map keeps insertion order
A JavaScript Map remembers the order keys were inserted (Lesson 64). So:
- The first key in the Map is the least recently used.
- To mark a key as recently used: delete it and set it again, which moves it to the end.
- To find the oldest:
map.keys().next().value.
All of these are O(1).
Solution with Map
class LRUCache {
#capacity;
#map = new Map();
constructor(capacity) {
if (capacity < 1) throw new RangeError("Capacity must be at least 1");
this.#capacity = capacity;
}
get(key) {
if (!this.#map.has(key)) return -1;
const value = this.#map.get(key);
this.#map.delete(key);
this.#map.set(key, value);
return value;
}
put(key, value) {
if (this.#map.has(key)) {
this.#map.delete(key);
}
this.#map.set(key, value);
if (this.#map.size > this.#capacity) {
const oldestKey = this.#map.keys().next().value;
this.#map.delete(oldestKey);
}
}
get size() {
return this.#map.size;
}
}Test it
const cache = new LRUCache(2);
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); 1
cache.put(3, 3); removes key 2
cache.get(2); -1
cache.put(4, 4); removes key 1
cache.get(1); -1
cache.get(3); 3
cache.get(4); 4The classic solution: hash map + doubly linked list
Some interviewers say "do not rely on Map's order". Then the classic design is:
- A hash map from key to a node, for O(1) lookup.
- A doubly linked list of nodes in usage order (Part 10). Each node points to the one before and after, so a node can be removed and moved to the front in O(1).
- Dummy head and tail nodes so you never have to check for empty edges.
head <-> [most recent] <-> ... <-> [least recent] <-> tailget: look up the node, move it to the front, return its value.put: if it exists, update and move to the front. Otherwise create a node at the front; if over capacity, remove the node before the tail and delete its key from the map.
Explain this design even if you code the Map version. Part 10 (linked lists) gives you the tools to write it.
Cost
| Operation | Time | Space |
|---|---|---|
| get | O(1) | |
| put | O(1) | |
| Total | O(capacity) |
Where LRU is used
- Browser and CDN caches.
- Database buffer pools.
- In-memory caches in Node.js servers (libraries such as
lru-cache). - Redis can be set to evict least recently used keys when memory is full.
Common mistakes
- Using an array and
indexOf/spliceto track order: O(n), which fails the requirement. - Forgetting that
getupdates the order. - Forgetting to delete before re-setting an existing key in
put, so its position does not change. - Evicting before inserting a key that already exists, removing the wrong item.
How to say it in an interview
"LRU evicts the least recently used entry when full. In JavaScript a Map preserves insertion order with O(1) operations, so on get I delete and re-insert the key to mark it most recent, and on put I do the same, then evict the first key from map.keys() if size exceeds capacity. Without relying on Map order, I would combine a hash map from key to node with a doubly linked list ordered by recency, using dummy head and tail nodes, which gives O(1) get and put."
Key words
| Word | Meaning |
|---|---|
| Cache | Fast storage for data that is likely to be needed again |
| Eviction | Removing an item to make space |
| LRU | Least Recently Used: evict the item unused for the longest |
| Capacity | The maximum number of items |
| Doubly linked list | A list where each node links to the previous and next |
| O(1) | Takes the same time however much data there is |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.