DSA · Patterns, not puzzles
How do you design an LRU cache?
Short answer
Combine a hash map for O(1) lookup with a doubly linked list for O(1) recency updates. On access, move the entry to the front; on insert past capacity, evict the least recently used entry at the back.
The cache must support get and put in O(1). A hash map alone gives lookup but not ordering. A linked list alone gives ordering but not lookup. Together, the map stores node references and the list maintains recency order.
class LRUCache {
constructor(capacity) {
this.capacity = capacity;
this.map = new Map();
}
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 oldest = this.map.keys().next().value;
this.map.delete(oldest);
}
}
}The classic linked-list version
- Use a dummy head and tail to avoid null checks at the boundaries
- The map key points to the linked-list node
- On get, unlink the node and insert it at the front
- On put, update or create a node at the front
- When over capacity, remove the node before the tail and delete its map entry
The Map-based implementation is concise and correct for JavaScript interviews. The linked-list version is what interviewers usually mean when they ask you to design the structure from scratch, because it demonstrates pointer manipulation and explicit O(1) reasoning.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why do you need both a hash map and a linked list?
- 2How do you make get and put O(1)?
- 3What changes for an LFU cache?
- 4How would you make the cache thread-safe?
Say it in the interview
I combine a hash map with a doubly linked list. The map gives constant-time lookup of a node, and the list keeps the most recently used items near the front. On get I move the node to the front; on put I insert or update at the front and evict from the back if over capacity. In JavaScript I can use Map insertion order, but I would explain the linked-list version to show the underlying O(1) design.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live DSA mock interview and get scored feedback on depth, clarity and confidence.