LeetCode #146 Medium

LRU Cache

LRU Cache is LeetCode 146 (Medium). Design a cache with a fixed capacity that throws out the least recently used key when it runs out of room. Implement the class LRUCache:

  • LRUCache(capacity) creates an empty cache that can hold capacity keys.
  • get(key) returns the value stored for key, or -1 if the key is not in the cache. A successful get counts as a use.
  • put(key, value) stores the pair. If the key already exists its value is replaced, and that also counts as a use. If adding a new key pushes the size past capacity, the key that was used longest ago is removed.

Both get and put must run in O(1) average time. There are up to 2 × 10⁵ calls and the capacity can be 3000, so anything that scans the cache per call is too slow.

Constraints
  • 1 <= capacity <= 3000
  • 0 <= key <= 10⁴
  • 0 <= value <= 10⁵
  • At most 2 * 10⁵ calls will be made to get and put.
designhash-tabledoubly-linked-list
Open on LeetCode ↗
02

Intuition

An lru cache has to answer two questions on every call, and each one needs a different structure:

  • Is this key here, and where? A hash map answers that in O(1), but a hash map has no idea which key was used last.
  • Which key is the oldest, and how do I mark this one as newest? A list kept in recency order answers that, but finding a key inside a list is O(n).

So keep both and let them point at the same objects. The list is a doubly linked list ordered from most recent (front) to least recent (back). The map stores key → node, not key → value. A lookup lands directly on the node; because the node knows both neighbours, it can be cut out and re-inserted at the front with four pointer writes. The node to evict is always the one at the back.

The list must be doubly linked: removing a node means rewiring the node before it, and only a prev pointer reaches that node without a scan.

How to spot this pattern

Whenever you are asked for least-recently-used eviction, or any "O(1) lookup plus O(1) reorder" structure, the answer is a hash map whose values are nodes of a linked list. The same pairing appears in LFU cache (one list per frequency), in an ordered set with insertion order, and in Python's OrderedDict itself.

03

Approach

Try it first

Before reading on, decide what the hash map's values should be, and write the exact pointer changes that move a node from the middle of a doubly linked list to its front. Then say why a singly linked list would not be enough.

1

The node and the two sentinels

Each node holds key, val, prev and next. The node stores its key so that, when it is evicted from the back of the list, the code knows which map entry to delete.

Create two dummy nodes, head and tail, linked to each other. Real nodes always sit between them, so every real node has a real neighbour on both sides: no None checks, and the empty cache is not a special case.

2

Two helpers do all the pointer work

  • remove(node): node.prev.next = node.next and node.next.prev = node.prev. The node is now out of the list.
  • add_front(node): place it between head and head.next, fixing four pointers.

Every operation below is a combination of these two.

3

get(key)

  • Key not in the map: return -1.
  • Otherwise take the node from the map, remove it and add_front it, because reading counts as a use. Return its value.
4

put(key, value)

  • If the key exists, remove its old node first.
  • Create a new node, store it in the map and add_front it.
  • If the map now holds more than capacity keys, the least recently used node is tail.prev. remove it and delete its key from the map.
5

Why this solution is O(1)

The map lookup is O(1) on average. remove and add_front change a fixed number of pointers and never walk the list, because the map hands over the node and the node carries its own prev. The list is always in recency order: each use moves exactly the used node to the front, so the back is the key whose last use is oldest.

04

Code in Python, C++ and Java

▶1class Node:
▶2 def __init__(self, key=0, val=0):
▶3 self.key, self.val = key, val
▶4 self.prev = self.next = None
▶5 
▶6 
▶7class LRUCache:
▶8 def __init__(self, capacity: int):
▶9 self.cap = capacity
▶10 self.map = {} # key -> node
▶11 self.head, self.tail = Node(), Node()
▶12 self.head.next, self.tail.prev = self.tail, self.head
▶13 
▶14 def _remove(self, node):
▶15 node.prev.next, node.next.prev = node.next, node.prev
▶16 
▶17 def _add_front(self, node):
▶18 node.prev, node.next = self.head, self.head.next
▶19 self.head.next.prev = node
▶20 self.head.next = node
▶21 
▶22 def get(self, key: int) -> int:
▶23 if key not in self.map:
▶24 return -1
▶25 node = self.map[key]
▶26 self._remove(node)
▶27 self._add_front(node)
▶28 return node.val
▶29 
▶30 def put(self, key: int, value: int) -> None:
▶31 if key in self.map:
▶32 self._remove(self.map[key])
▶33 node = Node(key, value)
▶34 self.map[key] = node
▶35 self._add_front(node)
▶36 if len(self.map) > self.cap:
▶37 lru = self.tail.prev
▶38 self._remove(lru)
▶39 del self.map[lru.key]
capacity 2, cache emptylist: key | valueheadnextprevtailmap: key → nodehead and tail are dummies: no null checks
capacity2keys before evicting
map{ }key → node
Setup. Two dummy nodes are linked to each other. Every real node will sit between them, so inserting into an empty list or removing the last real node is the same pointer work as anywhere else. The front (next to head) will be the most recent key, the back (next to tail) the least recent.
put(1, 1)list: key | valueheadnextprev11tailmap: key → node1added at the front
order[1]front = most recent
size1of 2
New key 1: build a node, point map[1] at it, and link it in after head as the most recent key.
put(2, 2)list: key | valueheadnextprev22MRU11LRUtailmap: key → node12added at the front
order[2, 1]front = most recent
size2of 2
New key 2: build a node, point map[2] at it, and link it in after head as the most recent key.
get(1)list: key | valueheadnextprev22MRU11LRUtailmap: key → node12hit: the map pointer finds the node in O(1)
key1found in the map
positionbackabout to be refreshed
Key 1 is in the map, and the map stores the node, not just the value. That pointer lands on the node wherever it sits, even at the back where it was next in line for eviction. Reading it counts as a use, so it must move to the front.
get(1)returns1list: key | valueheadnextprev11MRU22LRUtailmap: key → node12unlink, re-add after head
order[1, 2]front = most recent
returns1
remove joins the node's two neighbours to each other (its prev pointer is what makes the left neighbour reachable), then add_front slots it in after head. Four pointer writes, no scan. Key 2 is now the least recent. Return 1.
put(3, 3)list: key | valueheadnextprev33MRU1122LRUtailmap: key → node123size 3 > capacity 2
order[3, 1, 2]front = most recent
size3over capacity
New key 3: build a node, point map[3] at it, and link it in after head as the most recent key. The cache now holds 3 keys, one more than it may, so the least recent key must go.
put(3, 3)list: key | valueheadnextprev33MRU1122tailmap: key → node123evict tail.prev: key 2
tail.prevkey 2least recently used
mapdel 2
The least recently used key is always the node just before tail: key 2. Unlink it, then delete map[2]. That delete is only O(1) because the node stores its own key; the list is where the eviction starts, and the list alone cannot say which map entry to drop.
put(3, 3)list: key | valueheadnextprev33MRU11LRUtailmap: key → node13back to 2 of 2 keys
order[3, 1]front = most recent
size2of 2
Key 2 is gone from both structures, and they agree again: every map entry points at a live node, and every node between the sentinels has a map entry.
get(2)returns-1list: key | valueheadnextprev33MRU11LRUtailmap: key → node132not in mapmiss: the list is not touched
key2not in the map
returns-1nothing to refresh
One hash lookup says key 2 is not cached (it was evicted earlier). A miss is not a use, so the order [3, 1] stays exactly as it was. Return -1.
put(4, 4)list: key | valueheadnextprev44MRU3311LRUtailmap: key → node134size 3 > capacity 2
order[4, 3, 1]front = most recent
size3over capacity
New key 4: build a node, point map[4] at it, and link it in after head as the most recent key. The cache now holds 3 keys, one more than it may, so the least recent key must go.
put(4, 4)list: key | valueheadnextprev44MRU3311tailmap: key → node134evict tail.prev: key 1
tail.prevkey 1least recently used
mapdel 1
The least recently used key is always the node just before tail: key 1. Unlink it, then delete map[1]. That delete is only O(1) because the node stores its own key; the list is where the eviction starts, and the list alone cannot say which map entry to drop.
put(4, 4)list: key | valueheadnextprev44MRU33LRUtailmap: key → node34back to 2 of 2 keys
order[4, 3]front = most recent
size2of 2
Key 1 is gone from both structures, and they agree again: every map entry points at a live node, and every node between the sentinels has a map entry.
get(1)returns-1list: key | valueheadnextprev44MRU33LRUtailmap: key → node341not in mapmiss: the list is not touched
key1not in the map
returns-1nothing to refresh
One hash lookup says key 1 is not cached (it was evicted earlier). A miss is not a use, so the order [4, 3] stays exactly as it was. Return -1.
get(3)list: key | valueheadnextprev44MRU33LRUtailmap: key → node34hit: the map pointer finds the node in O(1)
key3found in the map
positionbackabout to be refreshed
Key 3 is in the map, and the map stores the node, not just the value. That pointer lands on the node wherever it sits, even at the back where it was next in line for eviction. Reading it counts as a use, so it must move to the front.
get(3)returns3list: key | valueheadnextprev33MRU44LRUtailmap: key → node34unlink, re-add after head
order[3, 4]front = most recent
returns3
remove joins the node's two neighbours to each other (its prev pointer is what makes the left neighbour reachable), then add_front slots it in after head. Four pointer writes, no scan. Key 4 is now the least recent. Return 3.
get(4)list: key | valueheadnextprev33MRU44LRUtailmap: key → node34hit: the map pointer finds the node in O(1)
key4found in the map
positionbackabout to be refreshed
Key 4 is in the map, and the map stores the node, not just the value. That pointer lands on the node wherever it sits, even at the back where it was next in line for eviction. Reading it counts as a use, so it must move to the front.
get(4)returns4list: key | valueheadnextprev44MRU33LRUtailmap: key → node34unlink, re-add after head
order[4, 3]front = most recent
returns4
remove joins the node's two neighbours to each other (its prev pointer is what makes the left neighbour reachable), then add_front slots it in after head. Four pointer writes, no scan. Key 3 is now the least recent. Return 4.
final state, capacity 2list: key | valueheadnextprev44MRU33LRUtailmap: key → node34every call was one lookup plus a few pointer writes
get results[1, -1, -1, 3, 4]
order[4, 3]most to least recent
Done. The get calls returned [1, -1, -1, 3, 4]. No operation ever walked the list: the map supplied the node, and the sentinels meant every node had neighbours to rewire, so both get and put are O(1).
05

Common pitfalls

Mapping key to value instead of key to node

✗ Wrong
self.map[key] = value
self.order.remove(key)  # list scan
self.order.append(key)
✓ Right
self.map[key] = node
self._remove(node)
self._add_front(node)

With only the value in the map, marking a key as used means finding it in the order list first, which is O(n) per call and times out at 2 × 10⁵ calls.

Forgetting that get is a use

✗ Wrong
def get(self, key):
    return self.map[key].val if key in self.map else -1
✓ Right
node = self.map[key]
self._remove(node)
self._add_front(node)
return node.val

Without the move, a key read a moment ago stays at the back and is the next one evicted. In the LeetCode example, get(1) must save key 1 so that put(3, 3) evicts key 2 instead.

Not storing the key inside the node

✗ Wrong
lru = self.tail.prev
self._remove(lru)
# which map entry is this?
✓ Right
lru = self.tail.prev
self._remove(lru)
del self.map[lru.key]

Eviction starts from the list, not from the map. If the node does not carry its key, there is no O(1) way to delete the matching map entry, and the map keeps a stale pointer that get would later return.

Evicting before inserting on an update

✗ Wrong
if len(self.map) == self.cap:
    evict()
self.map[key] = node
✓ Right
insert first, then
if len(self.map) > self.cap:
    evict()

Updating a key that is already present does not grow the cache. Evicting when the size equals capacity throws out an innocent key on every update. Checking > after inserting handles new keys and updates with the same line.

06

Edge cases

Capacity 1

Every put of a new key evicts the only other key. With the sentinels, the node at tail.prev is the old key right after the new one is added at the front, so no special case is needed.

put on an existing key

The old node is removed before the new one is added, so the size does not change and nothing is evicted. The key moves to the front because an update counts as a use.

get on the most recent key

The node is removed and re-added in the same place. Harmless, and cheaper than a branch that checks for it.

07

Complexity

Time
O(1) per get and put
Space
O(capacity)
Each call does one hash lookup and a fixed number of pointer writes. At most capacity + 1 nodes exist at once (briefly, before an eviction), plus the two sentinels.
08

LRU Cache FAQ

How do you implement an LRU cache in O(1)?
  • Structures: a hash map from key to node, and a doubly linked list with dummy head and tail, most recent at the front.
  • get: missing key returns -1; otherwise move the node to the front and return its value.
  • put: remove the old node if the key exists, add a new node at the front, and if the size exceeds capacity remove tail.prev and its key from the map.
  • Complexity: O(1) per operation, O(capacity) space.
Can I use OrderedDict in Python?

Yes. OrderedDict is itself a hash map plus a doubly linked list. move_to_end(key) marks a use and popitem(last=False) removes the oldest key. It is accepted on LeetCode, but interviewers who ask you to build it expect the hand-built version above. functools.lru_cache is a decorator that memoises function calls; it is not a class you can call get and put on.

How do you build one in Java with LinkedHashMap?

Construct it with access order on: new LinkedHashMap<>(16, 0.75f, true), then override removeEldestEntry to return size() > capacity. get and put reorder the entries automatically and the eldest is dropped after each insert. Like OrderedDict, it hides the mechanism the question is testing.

Why does it need a doubly linked list?

Removing a node from the middle of a list means changing the next pointer of the node before it. A singly linked list can only reach that node by walking from the head, which is O(n). With a prev pointer it is one step away.

What are dummy head and tail nodes for?

They guarantee every real node has a node on both sides. Without them, removing the first or last node, or inserting into an empty list, each need their own None checks, and those branches are where most LRU cache bugs come from.