Design an LRU cache with O(1) get and put
Company tags are compiled from public interview reports and are signals, not guarantees.
What interviewers are testing
LRU is the most common design question in coding rounds because it forces you to combine two data structures instead of pattern-matching one. Interviewers watch whether you decompose the operations first - lookup, unlink, move to front, evict - and whether your node management makes get and put O(1) without leaking stale links. It also reveals production awareness: the same design appears in Redis and database buffer pools, where approximation and concurrency change the answer.
Mental model
Two independent requirements must hold at once: find any key node in O(1) with a hash map, and reorder recency in O(1) with a doubly linked list. The map stores key to node, so you never search a list. The list stores recency order with the most recently used node at the head and the least recently used at the tail; a get unlinks its node and re-inserts it at the head, and a put at capacity evicts the tail. Sentinels remove null checks at both ends.
Step-by-step solution
Step 1: One structure cannot do both
Start by ruling out the obvious single structures. An array gives O(1) access by index, but a cache is keyed by arbitrary keys, so a get first has to find the key with a linear scan; even after that, removing an item from the middle shifts every later element, which is O(n) again. A plain object or dictionary gives O(1) keyed access, but it offers no supported move-to-front operation: deleting and re-adding a key is engine-dependent, integer-like keys iterate in numeric order rather than recency order, and nothing in the contract promises that iteration reflects access time. The animation shows each candidate operation and its cost: indexOf to locate, splice to unlink, unshift to promote. The pattern that emerges is the hint: one structure is good at lookup by key, another at reordering by position. Use one for each job and let node references connect them.
Step 2: Hash map plus linked list
The design splits responsibilities. A hash map stores key to node references, so lookup never scans - the map jumps straight to the node object. A doubly linked list stores recency, from the most recently used node at one end to the least recently used at the other, and because every node knows both neighbors, unlinking it and re-inserting it at the front are constant-time pointer updates. Two sentinel nodes, a dummy head and a dummy tail, bracket the list: head.next is always the MRU node and tail.prev is always the LRU node, so removing or inserting never special-cases an empty list. The animation lays out the wiring: map entries point at list nodes, nodes point at each other, and the two sentinels close the ends. Every operation now has a direct handle on the exact node it must move, which is the property neither structure has alone.
Step 3: A get promotes a node
A get does three things in constant time: look up the node in the map, unlink it from its current position, and insert it right after the dummy head. The animation warms the cache to c <-> b <-> a, with c most recent and a the next eviction victim, then calls get on a. The map finds a's node immediately; remove rewires a's neighbors to point at each other, splicing the node out; addFront reattaches it between the head sentinel and the previous first node. The return value comes from the node, not from a re-read of any structure. Unlink and insert have to happen before returning, because recency is part of the contract: a hit widens the gap between the touched node and eviction, while a miss returns -1 and touches nothing, so failed lookups cannot reshape the list.
Step 4: Put inserts and evicts
A put has two cases. If the key already exists, update the value and promote the node exactly like a get - no eviction, because the cache size did not change. If the key is new and the cache is at capacity, there is no room, so the least recently used node must leave first: it is exactly tail.prev, the sentinel's neighbor. The animation starts with capacity 3 and a full list b <-> c <-> a, then writes put(d, 4). The size check fires, the LRU node a is unlinked and its key is deleted from the map, and a fresh node is allocated, linked after the head, and registered in the map. Doing the eviction before the insertion is what keeps the cache from ever exceeding capacity, and using the tail sentinel means the victim costs no traversal - the structure already points at it.
Step 5: Complexity and production notes
The final accounting: get is O(1) average because the map lookup is the only hashing step and the two pointer operations are constant; put is O(1) average for the same reason, with eviction costing one unlink and one map delete; space is O(capacity) because each live key owns exactly one node and one map entry. The average qualifier matters: an adversarial key set that collides in the hash function can degrade lookups toward O(n), so production caches randomize hash seeds or accept the risk explicitly. Real systems rarely use exact LRU either. Redis, for example, samples a handful of keys and evicts the oldest among them, trading exactness for cheaper bookkeeping under concurrency. The animation tallies the pointer operations per call and shows the constant bound holding as the cache grows.
Edge cases & traps
- Capacity 0: put must be a no-op (or evict immediately) instead of inserting a node and then evicting it; decide the contract and document it.
- Capacity 1: an insert-then-evict order would remove the node just added - evict before inserting so the new node survives.
- Updating an existing key must not count as a new entry or trigger eviction, but it must still refresh recency by moving the node to the front.
- get on a missing key returns -1 and must leave the order untouched, or a read storm reshapes the cache and evicts hot data.
- Languages without GC: an unlinked node can still be reachable from elsewhere, so clear prev/next and erase the map entry to avoid dangling pointers and leaks.