Try it first — give it 25 minutes
0/4 revealedStuck? Take one hint at a time. The struggle is where the pattern sticks.
The problem in plain English
Build a class LRUCache. LRU stands for least recently used.
LRUCache(capacity)makes an empty cache that holds at mostcapacitykey-value pairs.get(key)returns the value forkey, or-1if it's not there. A successfulgetcounts as using the key.put(key, value)inserts the pair, or updates the value if the key exists. That also counts as using the key. If inserting a new key would make the cache too big, first evict (remove) the key that was used longest ago.
Both get and put must run in O(1) average time. Capacity is up to 3,000, and there are up to 200,000 calls.
Example with capacity 2: put(1,1), put(2,2), get(1) → 1. Now key 2 is the least recently used, so put(3,3) evicts it, and get(2) → -1.
Start with brute force
Keep a list of (key, value) pairs, ordered from least to most recently used.
get: scan the list for the key. If found, move it to the end and return its value.put: scan for the key. If found, update it and move it to the end. Otherwise, if full, remove the first pair; then append the new one.
It's correct, but every call scans the list (O(capacity)) and moving or removing from the front of an array shifts every element. With capacity 3,000 and 200,000 calls, that's around 600 million steps. The problem asks for O(1).
Building the intuition
Write down what each operation needs:
| Need | Good at it |
|---|---|
| Find a key's value fast | hash map: O(1) |
| Know which key is the oldest | a list kept in recency order: look at the end |
| Move a key to "most recent" | a linked list: unhook and reinsert in O(1), if you're already standing on the node |
No single structure does all three. So use two, and connect them. Keep the entries in a linked list ordered from most recent (front) to least recent (back). Keep a hash map from key to that key's list node. The map takes you to the node in O(1); the list lets you move it in O(1).
Why doubly linked? To unhook a node, you need to change its previous node's next. In a singly linked list, finding the previous node means walking from the head. That's O(n). If every node also stores prev, you can reach both neighbours directly.
Why store the key inside the node? When you evict the back node, you also have to delete it from the map. The map is keyed by key, so the node has to tell you its key.
The last piece is from earlier in this stage: dummy nodes. Put a fake head before the front and a fake tail after the back. These sentinels are never removed, so every real node always has a real prev and next. There's no "is the list empty?" or "is this the first node?" check anywhere.
The optimal approach
Two helpers do all the pointer work:
remove(node):node.prev.next = node.nextandnode.next.prev = node.prev.add_front(node): linknodebetweenheadandhead.next(four pointer updates).
Then:
get(key): ifkeyisn't in the map, return-1. Otherwiseremove(node),add_front(node), returnnode.val.put(key, value):- If
keyexists: updatenode.val, thenremoveandadd_frontit. Done. - Otherwise, if the map is full: the LRU node is
tail.prev.removeit and delete its key from the map. - Create a new node, put it in the map, and
add_frontit.
- If
The subtle detail is updating an existing key never evicts. The size doesn't change, so check "key exists?" before "is it full?". Get that order wrong and put on a full cache evicts a key it didn't need to.
The code
Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.
class CacheNode:
"""One entry in the recency list. It stores its key so eviction can delete it from the map."""
def __init__(self, key: int = 0, val: int = 0):
self.key = key
self.val = val
self.prev = None
self.next = None
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.nodes = {} # key -> CacheNode, for O(1) lookup
# Two sentinel nodes that are never removed, so every real node always has
# a prev and a next. head.next is the most recent; tail.prev the least.
self.head = CacheNode()
self.tail = CacheNode()
self.head.next = self.tail
self.tail.prev = self.head
def _remove(self, node: CacheNode) -> None:
# unhook node by joining its neighbours to each other
node.prev.next = node.next
node.next.prev = node.prev
def _add_front(self, node: CacheNode) -> None:
# slot node in right after head: it becomes the most recently used
node.prev = self.head
node.next = self.head.next
self.head.next.prev = node
self.head.next = node
def get(self, key: int) -> int:
node = self.nodes.get(key)
if node is None:
return -1
self._remove(node) # reading counts as a use,
self._add_front(node) # so move it to the front
return node.val
def put(self, key: int, value: int) -> None:
node = self.nodes.get(key)
if node is not None: # existing key: update it and mark it as just used
node.val = value
self._remove(node)
self._add_front(node)
return
if len(self.nodes) == self.capacity: # full: evict the least recently used
lru = self.tail.prev
self._remove(lru)
del self.nodes[lru.key] # this is why each node remembers its key
node = CacheNode(key, value)
self.nodes[key] = node
self._add_front(node)class LRUCache {
// One entry in the recency list. It stores its key so eviction can erase it from the map.
struct CacheNode {
int key, val;
CacheNode* prev = nullptr;
CacheNode* next = nullptr;
CacheNode(int k, int v) : key(k), val(v) {}
};
int capacity;
unordered_map<int, CacheNode*> nodes; // key -> node, for O(1) lookup
// Two sentinel nodes that are never removed, so every real node always has
// a prev and a next. head->next is the most recent; tail->prev the least.
CacheNode* head;
CacheNode* tail;
void remove(CacheNode* node) {
// unhook node by joining its neighbours to each other
node->prev->next = node->next;
node->next->prev = node->prev;
}
void addFront(CacheNode* node) {
// slot node in right after head: it becomes the most recently used
node->prev = head;
node->next = head->next;
head->next->prev = node;
head->next = node;
}
public:
LRUCache(int capacity) : capacity(capacity), head(new CacheNode(0, 0)), tail(new CacheNode(0, 0)) {
head->next = tail;
tail->prev = head;
}
~LRUCache() {
for (CacheNode* node = head; node != nullptr;) {
CacheNode* nxt = node->next;
delete node;
node = nxt;
}
}
int get(int key) {
auto it = nodes.find(key);
if (it == nodes.end()) return -1;
CacheNode* node = it->second;
remove(node); // reading counts as a use,
addFront(node); // so move it to the front
return node->val;
}
void put(int key, int value) {
auto it = nodes.find(key);
if (it != nodes.end()) { // existing key: update it and mark it as just used
CacheNode* node = it->second;
node->val = value;
remove(node);
addFront(node);
return;
}
if ((int)nodes.size() == capacity) { // full: evict the least recently used
CacheNode* lru = tail->prev;
remove(lru);
nodes.erase(lru->key); // this is why each node remembers its key
delete lru;
}
CacheNode* node = new CacheNode(key, value);
nodes[key] = node;
addFront(node);
}
};class LRUCache {
// One entry in the recency list. It stores its key so eviction can remove it from the map.
private static class CacheNode {
int key, val;
CacheNode prev, next;
CacheNode(int key, int val) {
this.key = key;
this.val = val;
}
}
private final int capacity;
private final Map<Integer, CacheNode> nodes = new HashMap<>(); // key -> node, for O(1) lookup
// Two sentinel nodes that are never removed, so every real node always has
// a prev and a next. head.next is the most recent; tail.prev the least.
private final CacheNode head = new CacheNode(0, 0);
private final CacheNode tail = new CacheNode(0, 0);
public LRUCache(int capacity) {
this.capacity = capacity;
head.next = tail;
tail.prev = head;
}
private void remove(CacheNode node) {
// unhook node by joining its neighbours to each other
node.prev.next = node.next;
node.next.prev = node.prev;
}
private void addFront(CacheNode node) {
// slot node in right after head: it becomes the most recently used
node.prev = head;
node.next = head.next;
head.next.prev = node;
head.next = node;
}
public int get(int key) {
CacheNode node = nodes.get(key);
if (node == null) return -1;
remove(node); // reading counts as a use,
addFront(node); // so move it to the front
return node.val;
}
public void put(int key, int value) {
CacheNode node = nodes.get(key);
if (node != null) { // existing key: update it and mark it as just used
node.val = value;
remove(node);
addFront(node);
return;
}
if (nodes.size() == capacity) { // full: evict the least recently used
CacheNode lru = tail.prev;
remove(lru);
nodes.remove(lru.key); // this is why each node remembers its key
}
node = new CacheNode(key, value);
nodes.put(key, node);
addFront(node);
}
}// One entry in the recency list. It stores its key so eviction can delete it from the map.
class CacheNode {
constructor(key = 0, val = 0) {
this.key = key;
this.val = val;
this.prev = null;
this.next = null;
}
}
class LRUCache {
/**
* @param {number} capacity
*/
constructor(capacity) {
this.capacity = capacity;
this.nodes = new Map(); // key -> CacheNode, for O(1) lookup
// Two sentinel nodes that are never removed, so every real node always has
// a prev and a next. head.next is the most recent; tail.prev the least.
this.head = new CacheNode();
this.tail = new CacheNode();
this.head.next = this.tail;
this.tail.prev = this.head;
}
remove(node) {
// unhook node by joining its neighbours to each other
node.prev.next = node.next;
node.next.prev = node.prev;
}
addFront(node) {
// slot node in right after head: it becomes the most recently used
node.prev = this.head;
node.next = this.head.next;
this.head.next.prev = node;
this.head.next = node;
}
/**
* @param {number} key
* @return {number}
*/
get(key) {
const node = this.nodes.get(key);
if (node === undefined) return -1;
this.remove(node); // reading counts as a use,
this.addFront(node); // so move it to the front
return node.val;
}
/**
* @param {number} key
* @param {number} value
* @return {void}
*/
put(key, value) {
let node = this.nodes.get(key);
if (node !== undefined) { // existing key: update it and mark it as just used
node.val = value;
this.remove(node);
this.addFront(node);
return;
}
if (this.nodes.size === this.capacity) { // full: evict the least recently used
const lru = this.tail.prev;
this.remove(lru);
this.nodes.delete(lru.key); // this is why each node remembers its key
}
node = new CacheNode(key, value);
this.nodes.set(key, node);
this.addFront(node);
}
}Dry run
Capacity 2. The list is written front (most recent) to back (least recent), without the sentinels.
| Call | Returns | What happened | List after |
|---|---|---|---|
put(1, 1) | – | new key | 1 |
put(2, 2) | – | new key | 2, 1 |
get(1) | 1 | found, moved to front | 1, 2 |
put(3, 3) | – | full: evict back (2), add 3 | 3, 1 |
get(2) | -1 | not in map | 3, 1 |
put(4, 4) | – | full: evict back (1), add 4 | 4, 3 |
get(1) | -1 | not in map | 4, 3 |
get(3) | 3 | found, moved to front | 3, 4 |
get(4) | 4 | found, moved to front | 4, 3 |
Look at put(3, 3). Key 1 was inserted before key 2, but get(1) touched it later, so key 2 is the one evicted. Recency of use, not insertion order.
Complexity
- Time: O(1) per call. A map lookup is O(1) on average, and
removeandadd_fronteach change a fixed number of pointers. - Space: O(capacity). The map and the list each hold at most
capacityentries, plus two sentinels.
Edge cases and traps
- Updating a key in a full cache. Must not evict anything. Check whether the key exists first.
- Forgetting that
getis a use. A hit must move the node to the front, or the wrong key gets evicted later. - Not storing the key in the node. Then eviction can't find the map entry to delete, and the map grows past capacity.
- Evicting from the wrong end. New and used nodes go to the front, so the LRU node is
tail.prev. Pick one convention and comment it. - Capacity 1. Every new key evicts the only one. The sentinels make this work with no special case.
add_frontin the wrong order. Set the new node's ownprevandnextfirst, then updatehead.next.prevbefore overwritinghead.next. Draw the four arrows on paper.
Say it in the interview
"I need O(1) lookup and O(1) 'which key is oldest', so I'll combine a hash map with a doubly linked list. The list keeps entries in recency order, most recent at the front. The map stores key to node, so I can jump to any node and unhook it in O(1); that's why it's doubly linked. Get and put both move the node to the front. When the cache is full, I evict the node before the tail sentinel and delete its key from the map, which is why each node stores its key. Sentinel head and tail nodes mean no null checks. Every operation is O(1)."
Follow-ups interviewers ask
- "Can you use a built-in?" Python's
OrderedDict(withmove_to_endandpopitem(last=False)) and Java'sLinkedHashMap(with access order andremoveEldestEntry) are exactly a hash map plus a doubly linked list. Mention them, but expect to be asked to build it by hand. - "Make it thread-safe." The simplest answer is one lock around
getandput, since both change the list. Finer-grained designs split the cache into several independently locked parts. - "What about LFU (least frequently used)?" That's LFU Cache. Keep a count per key and one doubly linked list per count, plus the current minimum count, so eviction is still O(1).
Practise the same idea
This is Day 50 of a free 90-day plan 🐸
90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.
Get the full roadmap — free