Design an LRU Cache
How the interviewer asks it
“Implement a least-recently-used cache with a fixed capacity. get(key) returns the value or -1, put(key, value) inserts or updates, and when the cache is full the least recently used entry is evicted. Both operations must be O(1).”
2 put 1 1 put 2 2 get 1 put 3 3 get 2 put 4 4 get 1 get 3 get 4
1 -1 -1 3 4
In the practice room your code reads the input from standard input, and Run checks it against tests like this one. Try it now in your browser, in Python or JavaScript.
Typed drills are free and unlimited: the AI scores your answer against the outline below.
What the interviewer is looking for
- You explain why neither a map alone (no order) nor a list alone (slow lookup) is enough, and combine them.
- Clean pointer handling: remove a node, add a node at the head, evict from the tail.
- You remember that get also counts as a use and moves the entry to the front.
- Sentinel head and tail nodes, or careful empty-list handling, so edge cases do not crash.
How to structure your answer
- 01
Clarify
Confirm capacity is at least 1, what put does on an existing key (update and refresh), and whether you may use the language's ordered map.
- 02
Data structures
A hash map from key to node, and a doubly linked list ordered from most to least recently used.
- 03
get
Look up the node. If missing return -1. Otherwise unlink it, move it to the head and return its value.
- 04
put
If the key exists, update the value and move it to the head. If not, create a node at the head; if size exceeds capacity, remove the tail node and delete its key from the map.
- 05
Test
Capacity 2: put 1, put 2, get 1, put 3 (evicts 2), get 2 returns -1. Walk it through out loud.
Best answers from candidates
No candidate answers yet. Type yours, and if it scores 6 or more you can show it here without your name.
Answers are shared by candidates, without names, after a privacy check. Add yours
Common mistakes
- Forgetting to remove the evicted key from the hash map, so the map grows forever.
- Not refreshing recency on get, which turns it into a FIFO cache.
- Using a singly linked list, which makes removing a node from the middle O(n).
- Reaching for a built-in ordered map without saying so; ask first, and be ready to build it by hand.
Follow-up questions to expect
- Make it safe for many threads without one global lock (striped locks or sharded caches).
- Add a time-to-live per entry.
- How would you change the eviction policy to least-frequently-used?
Now answer it out loud
Max will ask you this exact question, listen to your answer, push on the weak spots with follow-ups like the ones above, and score you when you finish.
Practice with MaxFree: a 5-minute voice round and unlimited typed drills, with scored feedback. No card, and your camera is never recorded.
More coding interview questions
Preparing for this round? Read how to prepare for a coding interview: a four-week DSA plan.