"Design an LRU cache" is the most-asked low-level design question in Indian product-company interviews, and it shows up in DSA rounds too. It is small enough to code in 30 minutes, but it tests three things at once: whether you can pick the right data structures, whether you can turn them into clean classes, and whether you can reason about what happens when real systems use your code: concurrently, with expiring entries, under memory pressure.
This article walks through the design the way you'd present it in an interview: requirements, the key insight, the classes, code in four languages, and the follow-ups.
Requirements
Clarify before you code. A typical version:
get(key)returns the value if present, otherwise-1(or "not found"). A successfulgetmarks the key as most recently used.put(key, value)inserts or updates the key and marks it most recently used.- The cache has a fixed capacity. When an insert would exceed it, evict the least recently used key.
- Both operations run in O(1) average time.
Good questions to ask: Can capacity be zero? Are keys and values integers or generic? Does put on an existing key count as a use? (Yes, almost always.) Is it used from multiple threads? (Often a follow-up, so mention it now and park it.)
The key insight: two structures, one job each
No single standard structure does both jobs in O(1):
- A hash map finds a key in O(1), but has no notion of order.
- A list ordered by recency knows who to evict, but finding a key in it is O(n).
The classic solution combines them. Keep a doubly linked list ordered from most to least recently used, and a hash map from key to list node. Then:
get: look up the node in the map (O(1)), unlink it and move it to the front (O(1) because the list is doubly linked and the node knows its neighbours).put: if the key exists, update and move to front. Otherwise create a node at the front; if over capacity, remove the node at the back (O(1)) and delete its key from the map, which is why each node stores its key.
Two sentinel nodes (a dummy head and a dummy tail that are never removed) eliminate every "is the list empty?" and "is this the first node?" special case. Interviewers notice this; it is the difference between 40 lines of edge cases and 10 clean ones.
The node right after the head is the most recently used; the node right before the tail is the next to be evicted.
Class design
Keep the responsibilities separate, because interviewers grade the design as much as the algorithm:
Node: key, value,prev,next. A plain data holder.- The list operations:
addToFront(node),remove(node),removeLast(). Small private helpers (or a separateDoublyLinkedListclass if you want to show OOP explicitly). LRUCache: owns the map and the list, exposes onlygetandput. Nothing outside it can see a node.
The implementation
class Node:
__slots__ = ("key", "value", "prev", "next")
def __init__(self, key=0, value=0):
self.key, self.value = key, value
self.prev = self.next = None
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.map = {} # key -> node
self.head, self.tail = Node(), Node() # sentinels
self.head.next, self.tail.prev = self.tail, self.head
def get(self, key: int) -> int:
node = self.map.get(key)
if node is None:
return -1
self._move_to_front(node)
return node.value
def put(self, key: int, value: int) -> None:
if self.capacity <= 0:
return
node = self.map.get(key)
if node is not None:
node.value = value
self._move_to_front(node)
return
if len(self.map) == self.capacity:
lru = self.tail.prev # least recently used
self._remove(lru)
del self.map[lru.key]
node = Node(key, value)
self.map[key] = node
self._add_to_front(node)
def _add_to_front(self, node: Node) -> None:
node.prev, node.next = self.head, self.head.next
self.head.next.prev = node
self.head.next = node
def _remove(self, node: Node) -> None:
node.prev.next, node.next.prev = node.next, node.prev
def _move_to_front(self, node: Node) -> None:
self._remove(node)
self._add_to_front(node)Walk through an example
Capacity 2:
| Operation | List (most → least recent) | Returns |
|---|---|---|
put(1, 10) | 1 | |
put(2, 20) | 2, 1 | |
get(1) | 1, 2 | 10 |
put(3, 30) | 3, 1 (evicts 2) | |
get(2) | 3, 1 | -1 |
put(1, 11) | 1, 3 (the update moves 1 to the front) | |
get(3) | 3, 1 | 30 |
Say this table out loud in the interview, or trace it on the code. It catches the two most common bugs: forgetting that get changes recency, and forgetting to remove the evicted key from the map.
Complexity
getandput: O(1) average: one hash lookup plus a constant number of pointer changes.- Space: O(capacity): one map entry and one node per key.
Shortcuts, and when not to use them
Most languages have an ordered map that does the list work for you:
- Java:
LinkedHashMapwithaccessOrder = true, overridingremoveEldestEntry. - Python:
collections.OrderedDictwithmove_to_endandpopitem(last=False). - JavaScript: a
Mapiterates in insertion order, so deleting and re-inserting a key moves it to the end, andmap.keys().next().valueis the oldest key.
Mention these, because it shows you know your language. But in a low-level design round, the interviewer almost always wants the hand-built version, because the point is to see you design the structure. Ask: "Shall I use LinkedHashMap, or would you like me to build the list?"
Follow-ups interviewers ask
Make it thread-safe
The simplest correct answer is one lock around get and put. Note that even get writes (it moves a node), so a read-write lock doesn't help: every operation needs exclusive access.
One lock becomes a bottleneck under heavy concurrency. The standard fix is sharding: split the cache into N independent LRU caches (each with its own lock), and route each key by hash(key) % N. Eviction becomes "least recently used within the shard", which is approximate but almost always acceptable. This is how libraries like Guava and Caffeine (Java) and many Go caches scale.
Add a time-to-live (TTL)
Store an expiresAt on each node. On get, treat an expired node as missing (remove it and return -1). That is lazy expiry: cheap, but expired entries still occupy space until someone touches them or they reach the tail. For tighter memory, add a background sweep, or keep a second structure (a min-heap or timing wheel ordered by expiry) to evict expired entries proactively. Redis combines lazy expiry with periodic random sampling.
Evict by frequency instead (LFU)
Least Frequently Used evicts the key with the fewest accesses, breaking ties by recency. The O(1) design keeps a map from key to node, a map from frequency to a doubly linked list of nodes with that frequency, and the current minimum frequency. It is a common "harder version". Know the shape even if you don't code it.
Size by bytes, not entries
Real caches limit memory, not key counts. Track each entry's size and evict from the tail until the total fits. Large values can force several evictions for one insert.
How it's used in real systems
LRU is everywhere: database buffer pools, CPU caches (approximately), CDN edge caches, and application caches in front of slow services. It works well when recent use predicts future use, and badly for scans that touch every item once, which flush everything useful. That is why databases often use variants like LRU-K or a "midpoint insertion" strategy. Our caching strategies article covers how caches like this fit into a larger system.
Edge cases to test
- Capacity 0 (or 1).
puton an existing key updates the value and recency.geton a missing key.- Evicting the only key.
- A long sequence of puts larger than capacity, where the map size must never exceed capacity.
Practise it in the LRU Cache problem, where hidden tests include large sequences that will catch an O(n) shortcut.