LRU Cache (LeetCode 146): Solution and Explanation
Design a fixed-capacity key-value cache with get and put operations. Reading or writing a key marks it as the most recently used, and when an insert pushes the cache over capacity, the least recently used key is evicted. Both operations must run in O(1) average time.
Watch it run step by step
Try your own input and write the code →Intuition
A first attempt usually stores the pairs in a dictionary and keeps a separate list of keys in usage order. Lookups are fast, but moving a key to the end of the list on every access means finding it first, which is O(n). Another idea is to store a timestamp per key and scan for the smallest on eviction, which makes put O(n) instead.
To make every operation O(1), you need two abilities at once: find a key's entry instantly, and reorder or remove that entry instantly. A hash map gives the first. A doubly linked list gives the second, because once you hold a pointer to a node you can unlink it and splice it at the tail in constant time. The classic design keeps both: the map stores key to node, and the list keeps nodes in recency order with the least recently used at the head.
Python ships this exact combination as collections.OrderedDict, which is a dictionary backed by a doubly linked list. Its move_to_end marks a key as most recent, and popitem(last=False) removes the oldest one, both in O(1). The reference solution leans on it, and the Java and C++ versions build the same structure explicitly. In an interview, be ready to explain or write the linked list yourself, since that is what the question is really probing.
Approach: Hash map with ordered recency (OrderedDict)
- Store
capacityand create an emptyOrderedDictnamedcache. Its order runs from least to most recently used. - In
get, return -1 if the key is missing. - Otherwise call
move_to_end(key)to mark it as the most recent and return its value. - In
put, if the key already exists, move it to the end first so the update counts as a use. - Assign
cache[key] = value. A new key is appended at the most recent end automatically. - If the size now exceeds
capacity, callpopitem(last=False)to evict the least recently used entry.
Step-by-step example
capacity = 2, then put(1,1), put(2,2), get(1), put(3,3), get(2), put(4,4), get(1), get(3), get(4)
- After put(1,1) and put(2,2), the order from oldest to newest is 1, 2.
- get(1) returns 1 and moves key 1 to the end, so the order is 2, 1.
- put(3,3) makes the size 3, so the oldest key, 2, is evicted. The order is 1, 3, and the following get(2) returns -1.
- put(4,4) overflows again and evicts key 1, leaving 3, 4. So get(1) returns -1.
- get(3) returns 3 and moves it to the end, then get(4) returns 4. The outputs match the expected [1, -1, -1, 3, 4].
Code: Python, Java, C++
1class LRUCache:
2 def __init__(self, capacity: int):
3 self.capacity = capacity
4 self.cache = OrderedDict()
5
6 def get(self, key: int) -> int:
7 if key not in self.cache:
8 return -1
9 self.cache.move_to_end(key)
10 return self.cache[key]
11
12 def put(self, key: int, value: int) -> None:
13 if key in self.cache:
14 self.cache.move_to_end(key)
15 self.cache[key] = value
16 if len(self.cache) > self.capacity:
17 self.cache.popitem(last=False)1class LRUCache {
2 private int capacity;
3 private LinkedHashMap<Integer, Integer> cache;
4
5 public LRUCache(int capacity) {
6 this.capacity = capacity;
7 this.cache = new LinkedHashMap<>(capacity, 0.75f, true) {
8 protected boolean removeEldestEntry(Map.Entry eldest) {
9 return size() > capacity;
10 }
11 };
12 }
13
14 public int get(int key) {
15 return cache.getOrDefault(key, -1);
16 }
17
18 public void put(int key, int value) {
19 cache.put(key, value);
20 }
21}1class LRUCache {
2 int capacity;
3 list<pair<int, int>> cache;
4 unordered_map<int, list<pair<int, int>>::iterator> map;
5
6public:
7 LRUCache(int capacity) : capacity(capacity) {}
8
9 int get(int key) {
10 if (map.find(key) == map.end()) return -1;
11 cache.splice(cache.begin(), cache, map[key]);
12 return map[key]->second;
13 }
14
15 void put(int key, int value) {
16 if (map.find(key) != map.end()) {
17 map[key]->second = value;
18 cache.splice(cache.begin(), cache, map[key]);
19 return;
20 }
21 if (cache.size() == capacity) {
22 map.erase(cache.back().first);
23 cache.pop_back();
24 }
25 cache.push_front({key, value});
26 map[key] = cache.begin();
27 }
28};Time and space complexity
O(1) per operation
Dictionary lookups, move_to_end and popitem(last=False) all run in constant time on average, because the ordered dictionary unlinks and relinks list nodes it can find through the hash table.
O(capacity)
The cache never holds more than capacity entries at the end of an operation, and each entry costs one map slot and one list node.
Other approaches
Hash map plus a hand-written doubly linked list (time O(1) per operation, space O(capacity))
Keep sentinel head and tail nodes, a map from key to node, and helpers to remove a node and insert one before the tail. This is the version interviewers usually expect and it is what the Java and C++ references implement.
Dictionary with timestamps (time O(capacity) per put, space O(capacity))
Store each key with the time of its last use and scan for the oldest timestamp when evicting. It is simple but makes each eviction O(capacity), which fails the O(1) requirement.
Common mistakes
- Forgetting that
getcounts as a use. If you do not move the key on a read, the wrong entry gets evicted later. - Evicting before inserting when the key already exists. Updating an existing key never grows the cache, so only check capacity after the assignment.
- In a hand-written list, removing a node from the list but not deleting its key from the map, or the reverse. The two structures must always agree.
- Using a singly linked list. Unlinking a node in O(1) needs its predecessor, which only a doubly linked list gives you directly.
Frequently asked questions
Why does an LRU cache use a hash map and a doubly linked list?
The hash map finds any entry in O(1), and the doubly linked list can move or remove a known node in O(1). Neither alone supports both fast lookups and fast reordering, but together they make every operation constant time.
Is using OrderedDict allowed in an interview?
Many interviewers accept it if you explain that it is a hash map backed by a doubly linked list. Some will then ask you to implement the list yourself, so it is worth practicing both versions.
What is the difference between LRU and LFU caching?
LRU evicts the entry that was used longest ago, while LFU evicts the entry used the fewest times, breaking ties by recency. LFU needs extra bookkeeping, usually a map from frequency to an ordered set of keys.
How would you make an LRU cache thread-safe?
Wrap get and put in a lock, because both mutate the ordering. For heavy concurrency, real systems shard the cache into several independently locked segments or use approximate recency to reduce contention.