LRU Cache solution explained
An LRU cache solution pairs a hash map with a doubly linked list: the map finds any entry in O(1), and the list keeps entries in order of last use so the least recently used one sits at the tail, ready to evict. Every get and put moves the touched entry to the front, so both operations run in O(1) average time.
By Evin JohnPublished 9 min read
The design task in your own words
Build a small store that holds at most a fixed number of key-value pairs, set when it is created. It offers two operations. get(key) returns the stored value, or a marker such as -1 when the key is absent, and counts as a use of that key. put(key, value) inserts a new pair or updates an existing one, which also counts as a use. If a new key arrives when the store is full, first throw out the key that has gone the longest without being used. Both operations should take constant time on average.
| Call | Result | Contents after, most recent first |
|---|---|---|
| put(7, 70) | 7 | |
| put(3, 30) | 3, 7 | |
| put(5, 50) | 5, 3, 7 (now full) | |
| get(7) | 70 | 7, 5, 3 |
| put(9, 90) | 9, 7, 5 (3 was least recent, so it is evicted) | |
| get(3) | -1 | 9, 7, 5 (a miss changes nothing) |
| put(5, 55) | 5, 9, 7 (an update also counts as a use) | |
| put(2, 20) | 2, 5, 9 (7 is evicted) | |
| get(5) | 55 | 5, 2, 9 |
Ask whether updating an existing key refreshes its recency (usually yes), what get should return for a miss, whether capacity can be zero, and whether the cache will be used from several threads. The last question shapes the follow-up discussion more than the first version of the code.
Why this one gets asked
LRU Cache sits between an algorithm problem and a design problem. There is no clever trick to discover; the challenge is to see that no single standard structure does the job and to combine two of them without bugs in the pointer updates. Interviewers use it in later rounds for that reason, and because it leads naturally into real systems questions about caches, memory limits and concurrency.
Follow-ups you should be ready for
- Make it thread-safe. The map and the list must change together, so a single lock around each operation is the simple answer. Then discuss contention, and splitting the cache into shards that each have their own lock.
- Add expiry. Store a timestamp per entry and treat expired entries as misses on read. A background sweep or a second ordering by expiry time keeps memory from filling with stale entries.
- Evict by least frequently used instead. LFU needs counts per key and a way to find the lowest count fast, usually buckets of keys per count with a pointer to the minimum.
- Limit by bytes, not by item count. Track total size and evict from the tail in a loop until the new entry fits.
- Scale it across machines. That turns into a caching discussion: partitioning keys, invalidation and what an approximate LRU gives up. The caching guide covers that side.
The slow designs, and why they fall short
A natural first idea is a dictionary for values plus a plain list of keys in recency order. Lookup is fast, but moving a key to the front means finding and removing it from the middle of the list, which is O(n). Another idea stores a last-used counter next to each value and scans for the smallest counter when evicting. Reads become O(1) and updates are cheap, but every eviction is an O(n) scan. Both are correct, and both are worth one sentence each before you explain what fixes them.
The fix is to keep the recency order in a doubly linked list and to store, in the dictionary, a reference to each key's node rather than its position. With a direct reference and links in both directions, removing a node from the middle is O(1). Adding at the front and removing at the tail are O(1) too.
Optimal design: hash map plus doubly linked list
- Two sentinel nodesA dummy head and a dummy tail mean every real node always has neighbors, so there are no special cases for an empty or one-item list.
- getLook the key up in the map. On a miss, return the marker. On a hit, unlink the node and reinsert it right after the head, then return its value.
- put on an existing keyUpdate the value in the node and move the node to the front, exactly like a hit.
- put on a new keyIf the cache is full, take the node just before the tail sentinel, unlink it and delete its key from the map. Then create the new node, add it to the map and insert it after the head.
Each node stores its key as well as its value. That looks redundant until you evict: the tail node is all you have, and you need its key to delete the map entry.
class _Node:
__slots__ = ("key", "val", "prev", "next")
def __init__(self, key=None, val=None):
self.key, self.val = key, val
self.prev = self.next = None
class RecentCache:
def __init__(self, capacity):
self.capacity = capacity
self.index = {} # key -> node
self.head = _Node() # sentinel beside the most recent entry
self.tail = _Node() # sentinel beside the least recent entry
self.head.next, self.tail.prev = self.tail, self.head
def _unlink(self, node):
node.prev.next, node.next.prev = node.next, node.prev
def _push_front(self, node):
node.prev, node.next = self.head, self.head.next
self.head.next.prev = node
self.head.next = node
def get(self, key):
node = self.index.get(key)
if node is None:
return -1
self._unlink(node)
self._push_front(node)
return node.val
def put(self, key, val):
if self.capacity <= 0:
return
node = self.index.get(key)
if node is not None:
node.val = val
self._unlink(node)
self._push_front(node)
return
if len(self.index) == self.capacity:
oldest = self.tail.prev
self._unlink(oldest)
del self.index[oldest.key]
node = _Node(key, val)
self.index[key] = node
self._push_front(node)#include <list>
#include <unordered_map>
#include <utility>
class RecentCache {
public:
explicit RecentCache(int capacity) : cap_(capacity) {}
int get(int key) {
auto it = where_.find(key);
if (it == where_.end()) return -1;
order_.splice(order_.begin(), order_, it->second); // now most recent
return it->second->second;
}
void put(int key, int value) {
if (cap_ <= 0) return;
auto it = where_.find(key);
if (it != where_.end()) {
it->second->second = value;
order_.splice(order_.begin(), order_, it->second);
return;
}
if (static_cast<int>(order_.size()) == cap_) {
where_.erase(order_.back().first); // least recent is at the back
order_.pop_back();
}
order_.emplace_front(key, value);
where_[key] = order_.begin();
}
private:
using Entry = std::pair<int, int>;
int cap_;
std::list<Entry> order_; // front = most recently used
std::unordered_map<int, std::list<Entry>::iterator> where_;
};The library shortcut, and when to use it
Python's OrderedDict already keeps insertion order with O(1) moves, and Java's LinkedHashMap can be built in access order with an override that removes the eldest entry. Showing the shortcut is fine once you have said what it does inside, but many interviewers ask you to build the list yourself, so lead with the full version unless told otherwise.
from collections import OrderedDict
class RecentCacheShort:
def __init__(self, capacity):
self.capacity = capacity
self.data = OrderedDict()
def get(self, key):
if key not in self.data:
return -1
self.data.move_to_end(key)
return self.data[key]
def put(self, key, val):
if self.capacity <= 0:
return
if key in self.data:
self.data.move_to_end(key)
self.data[key] = val
if len(self.data) > self.capacity:
self.data.popitem(last=False)Running time and memory
| Design | get | put | Memory |
|---|---|---|---|
| Dictionary plus a plain list of keys | O(c) to reorder | O(c) | O(c) |
| Dictionary with last-used counters | O(1) | O(c) when evicting | O(c) |
| Dictionary plus doubly linked list | O(1) average | O(1) average | O(c), with two pointers per entry |
Edge cases
- Capacity of one, where every new key evicts the previous one.
- Capacity of zero: decide whether put stores nothing or raises an error. Both versions above store nothing.
- Updating a key that already exists when the cache is full. It must not evict anything.
- A get on a missing key must not change the order.
- Many repeated gets on the same key, which should leave the order unchanged after the first.
Bugs interviewers often see
- Evicting before checking whether the key already exists, which throws out a good entry on a plain update.
- Forgetting to delete the evicted key from the map, so the map grows while the list stays small.
- Not storing the key in the node, then having no way to remove the map entry on eviction.
- Updating only one of the two pointers when unlinking, which corrupts the list silently until a later call.
- Treating a put on an existing key as not counting toward recency without asking.
Explaining the design aloud
Fictional example
- Candidate
- I need fast lookup by key and fast access to the oldest entry. A dictionary gives the first and a list gives the second, but moving something to the front of an array-backed list is linear.
- Candidate
- So I use a doubly linked list and store node references in the dictionary. With a reference, unlinking a node is constant time, and sentinels at both ends remove the empty-list special cases.
- Candidate
- A hit moves the node to the front. A new key on a full cache removes the node before the tail sentinel and its dictionary entry. Every step is constant time on average.
Next problems to try
The dictionary half of this design is the same tool used in Two Sum and Top K Frequent Elements. For traversal practice after a design problem, Number of Islands is a good change of pace. The coding problems hub lists the whole set, and the system design hub picks up where cache design meets real infrastructure.
Natively during preparation
A design problem like this is good to rehearse aloud. Natively, a desktop app for Mac and Windows, can read the prompt from a screenshot during practice and suggest the two-structure design and the follow-ups worth preparing, and it transcribes the mock session so you can check whether your explanation of eviction was clear. See the AI interview assistant for how practice sessions work.
Questions people ask
How do you implement an LRU cache in O(1)?
Combine a hash map from key to node with a doubly linked list ordered by recency. The map finds a node in O(1), the list moves it to the front or removes the least recent node from the tail in O(1).
Why a doubly linked list and not a singly linked one?
Removing a node from the middle needs its previous node. With links in both directions you can unlink any node you hold a reference to in constant time.
Can I use OrderedDict or LinkedHashMap in an interview?
Often yes, after you explain what they do inside. Many interviewers ask you to build the list yourself first, so be ready for both.
What follow-up questions come after LRU Cache?
Thread safety, time-based expiry, an LFU variant, limits by bytes instead of item count, and how the idea scales to a distributed cache.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
