Maintain a bounded key-value cache that evicts the least recently used entry when a new entry needs room.
Problem
Input. A nonnegative integer capacity, followed by get(key) and put(key, value) calls with integer keys and values.
Output. A successful get returns the stored value; a missing key returns -1.
A put stores or updates the value without returning one.
Rules. A successful read or any write makes that key most recently used; a miss does not change recency. If a new key exceeds capacity, remove the least recently used entry. Capacity counts entries, not bytes or time. Capacity zero retains nothing.
Example. With capacity 2, call put(1, 10), put(2, 20), get(1), then put(3, 30).
The read returns 10; key 2 is evicted, so get(2) returns -1.
Picture
The map locates a node directly by key.
Between the least and most sentinels, each adjacency has both next and previous links.
The leftmost real node is the eviction candidate.
| Operation | Returned value | Keys from least to most recent |
|---|---|---|
put(1,10) | None | 1 |
put(2,20) | None | 1,2 |
get(1) | 10 | 2,1 |
put(3,30) | None | 1,3; key 2 evicted |
get(2) | -1 | 1,3; unchanged |
At public operation boundaries, map entries and interior list nodes correspond one-to-one.
Every neighboring pair agrees in both link directions.
To unlink a node, join its previous and next neighbors directly in both directions.
To refresh it, insert it immediately before most.
To evict, remove least.next from the chain and delete its map entry.
The frames include transient detachment and overflow, where public-boundary agreement does not yet hold. The new node briefly raises size to three before eviction restores capacity two.
Problem trace
Reading key 1 moves it ahead of key 2 for the next eviction
Reference drawing
Problem trace
Reading key 1 moves it ahead of key 2 for the next eviction
Execution trace
- input
- capacity=2; put(1,10), put(2,20), get(1), put(3,30), get(2)
- bidirectional
- true
- map
- {}
- map
- {}→1 -> node1(value=10)
- size
- 0 / 2→1 / 2
- rewires
- not shown→least <-> 1 <-> most
- map
- 1 -> node1(value=10)→1 -> node1(value=10), 2 -> node2(value=20)
- size
- 1 / 2→2 / 2
- rewires
- least <-> 1 <-> most→1 <-> 2 <-> most
- detached
- not shown→node1(value=10)
- rewires
- 1 <-> 2 <-> most→least <-> 2
- size
- 2 / 2→not shown
- result
- not shown→get(1) = 10
- rewires
- least <-> 2→2 <-> 1 <-> most
- detached
- node1(value=10)→not shown
- map
- 1 -> node1(value=10), 2 -> node2(value=20)→1 -> node1(value=10), 2 -> node2(value=20), 3 -> node3(value=30)
- size
- not shown→3 / 2
- decision
- not shown→3 > 2 -> evict least.next
- detached
- not shown→node2(value=20)
- rewires
- not shown→least <-> 1
- size
- 3 / 2→not shown
- map
- 1 -> node1(value=10), 2 -> node2(value=20), 3 -> node3(value=30)→1 -> node1(value=10), 3 -> node3(value=30)
- size
- not shown→2 / 2
- evicted
- not shown→key 2
- lookup
- not shown→2 not in map
- result
- not shown→get(2) = -1
- size
- 2 / 2→not shown
- Recognize it
- The interface requires both O(1) key lookup and O(1) least-recent eviction, which no single ordinary array, map, or queue provides alone.
- Keep true
- Every map entry points to exactly one node between the sentinels, and list order is least-recent to most-recent; successful access moves that same key to the right edge.
- Reuse it
- Combine an index with an ordered linked structure whenever a system needs direct identity lookup plus constant-time promotion, removal, or boundary eviction.
Code
from __future__ import annotations
from dataclasses import dataclass
@dataclass(eq=False, slots=True)
class _CacheNode:
key: int = 0
value: int = 0
previous: _CacheNode | None = None
next: _CacheNode | None = None
class LRUCache:
def __init__(self, capacity: int) -> None:
self.capacity = capacity
self.nodes: dict[int, _CacheNode] = {}
self.least = _CacheNode()
self.most = _CacheNode()
self.least.next = self.most
self.most.previous = self.least
def _remove(self, node: _CacheNode) -> None:
node.previous.next = node.next
node.next.previous = node.previous
def _append(self, node: _CacheNode) -> None:
node.previous = self.most.previous
node.next = self.most
self.most.previous.next = node
self.most.previous = node
def get(self, key: int) -> int:
if key not in self.nodes:
return -1
node = self.nodes[key]
self._remove(node)
self._append(node)
return node.value
def put(self, key: int, value: int) -> None:
if key in self.nodes:
self._remove(self.nodes[key])
node = _CacheNode(key, value)
self.nodes[key] = node
self._append(node)
if len(self.nodes) > self.capacity:
removed = self.least.next
self._remove(removed)
del self.nodes[removed.key]
Pointer rewires take constant work; key lookup is expected under ordinary hashing assumptions, not a worst-case guarantee. Steady storage is for capacity , including two sentinels. Zero capacity immediately evicts every inserted entry.
An existing-key put allocates a replacement node here; a successful get moves the same node.
Misses return -1, which is indistinguishable from a stored -1 by return value alone.
Failure Check
Unlinking without map deletion leaves an evicted key readable. Updating only one link direction breaks later removals. A plain list also needs a linear scan to locate an arbitrary accessed key.
Change to Nonpromoting Observation
New task: Read a value without protecting its key from eviction.
Picture and change: Look up the value without unlinking or appending.
This driver accepts put, get and peek records and returns reads plus final key order.
def cache_peek_trace(capacity, operations):
cache, reads = LRUCache(capacity), []
for operation in operations:
name, *arguments = operation
if name == "put":
cache.put(*arguments)
elif name == "get":
reads.append(cache.get(*arguments))
else:
node = cache.nodes.get(arguments[0])
reads.append(node.value if node is not None else -1)
order, node = [], cache.least.next
while node is not cache.most:
order.append(node.key)
node = node.next
return [reads, order]
Check: Put keys 1,2, peek 1, then put 3: order becomes [2,3] and a subsequent get(1) misses.
Replacing that peek with get would instead evict key 2.
Use when: Monitoring must not change replacement decisions.
Change Entry Capacity
New task: Resize an existing cache to a nonnegative capacity.
Picture and change: Update capacity and repeatedly evict the least-recent node until size fits.
def resized_cache_keys(capacity, entries, new_capacity):
if new_capacity < 0:
raise ValueError("negative capacity")
cache = LRUCache(capacity)
for key, value in entries:
cache.put(key, value)
cache.capacity = new_capacity
while len(cache.nodes) > new_capacity:
removed = cache.least.next
cache._remove(removed)
del cache.nodes[removed.key]
keys, node = [], cache.least.next
while node is not cache.most:
keys.append(node.key)
node = node.next
return keys
Check: Entries [(1,10),(2,20),(3,30)], capacity 3, then new capacity 1 leave [3].
Shrinking to zero removes all entries.
The resize loop costs one eviction per removed entry, not constant time.
This complete helper also constructs the cache and lists its remaining keys.
Use when: The allowed entry count changes during operation.
Transfer Check
Does recency ordering also solve expiry or byte-weighted capacity?
Answer
No. Expiry needs time-validity rules, and weighted capacity needs per-entry weights with possibly several evictions per insertion.