
LRU Cache Implementation in Python: O(1) Get and Put
LRU cache implementation in Python with a hash map and a doubly linked list: O(1) get and put, runnable code, real output, a Java version and drills.
OOP in Practice · Episode 9 of 70 · Low-Level Design Problems · Intermediate · Python 3.13.18
The problem
You’re building the Python client for a product-catalogue API. Pages ask for the same products again and again, and every call is a slow network round trip. An LRU cache implementation fixes this: keep recent products in memory and, when full, drop the one unused for longest. The twist: reads and writes must both be O(1).
Your task: design an LRUCache class with O(1) get and put, and a ProductClient that uses it to avoid repeat API calls.
Requirements
get(key)returns the cached value and marks it most recently used; a miss returns a caller-chosen default.put(key, value)inserts or updates. When the cache is full and the key is new, the least recently used entry is evicted.- Updating an existing key never evicts anything.
- A cached
None(an unknown SKU, a 404) must be distinguishable from “not cached”. - Invalid capacity is rejected. Callers can observe evictions and hit/miss counts.
Constraints and assumptions
- Single process, single thread, in memory, standard library only.
- No time-based expiry (that’s a practice exercise).
- SKUs, names and prices are practice data; prices are whole paise to avoid float rounding.
What this tests: encapsulation, hash map + doubly linked list, composition, O(1) reasoning.
An O(1) LRU cache implementation combines two structures. A dict maps each key to a node, and a doubly linked list keeps the nodes in recency order, most recent at the front. get finds the node and moves it to the front. put adds at the front and, when full, unlinks the tail node.
Try it yourself first — hint
A dict can’t tell you which key is oldest; a list can’t find a key quickly. What if each dict value pointed straight into the list?
Step 1: Identify the objects and responsibilities
The nouns are cache, entry, recency order, client and API. Each gets one job.
| Class / interface | Responsibility | Key methods |
|---|---|---|
LRUCache[K, V] |
Public API. Enforces capacity, picks the victim, counts hits and misses. | get, put, keys, stats, in, len |
_RecencyList |
Private doubly linked list with sentinel ends. Knows order, not capacity. | push_front, unlink, move_to_front, pop_back |
_Node |
One entry: key, value, prev, next. | (data only, __slots__) |
ProductClient |
Read-through: cache first, else call the API and store the result. | product(sku) |
FakeProductApi |
Stands in for the slow HTTP API; counts calls. | fetch(sku) |
Step 2: The naive approach and why it breaks
A common first version keeps a dict for values and a Python list for order. It looks right on three keys.
class NaiveLRU:
def __init__(self, capacity):
self.capacity = capacity
self.data = {}
self.order = [] # oldest key first
def get(self, key):
if key not in self.data:
return None # same as a cached None
self.order.remove(key) # O(n) scan
self.order.append(key)
return self.data[key]
def put(self, key, value):
if len(self.data) >= self.capacity: # bug: also fires for updates
oldest = self.order.pop(0) # O(n) shift
del self.data[oldest]
if key in self.data:
self.order.remove(key)
self.data[key] = value
self.order.append(key)
c = NaiveLRU(2); c.put("A1", 299); c.put("B2", 1499); c.put("B2", 1399)
print(c.data, "<- A1 evicted by an update")
{'B2': 1399} <- A1 evicted by an update
- Updates evict innocent entries. The capacity check runs before the “key exists” check, so re-pricing
B2in a full cache threw outA1. - Every access is O(n).
list.removescans andpop(0)shifts every element. The benchmark below measures it. - A miss looks like a cached
None. A cached 404 looks like “never fetched”, so the API is called again. - No guard rails.
NaiveLRU(0)raisesIndexErroron the firstput, and publicdataandorderlet callers desync them.
Step 3: The design
+-------------------+ uses +------------------------------+
| ProductClient |--------->| LRUCache[K, V] |
|-------------------| |------------------------------|
| + product(sku) | | - _capacity: int |
+-------------------+ | - _index: dict[K, _Node] |
| uses | - _order: _RecencyList |
v | - _on_evict: callback | None |
+-------------------+ |------------------------------|
| FakeProductApi | | + get(key, default) |
| + fetch(sku) | | + put(key, value) |
+-------------------+ | + keys() / stats() / in, len |
+------------------------------+
| has-a | has-a
v v
dict key -> _Node _RecencyList (sentinels)
| head <-> n <-> n <-> tail
+-----------> (MRU) (LRU)
same node objects live in both
The trick is that the dict and the list share the same node objects. The dict finds a key’s node in O(1); the node’s prev and next pointers unlink it in O(1). Sentinel head and tail nodes remove every “first or last node?” branch.
This is encapsulation doing real work. The dict and the list must always agree, so neither is public. It is also composition over inheritance: LRUCache has a dict and a list rather than subclassing dict, so no inherited method can bypass the eviction rule.
Step 4: The LRU cache implementation in Python
"""LRU cache implementation: hash map + doubly linked list, O(1) get and put."""
from __future__ import annotations
from dataclasses import dataclass
from typing import Callable, Generic, Hashable, Optional, TypeVar
K = TypeVar("K", bound=Hashable)
V = TypeVar("V")
class _Node(Generic[K, V]):
"""One cache entry, linked to its neighbours in recency order."""
__slots__ = ("key", "value", "prev", "next")
def __init__(self, key: K, value: V) -> None:
self.key, self.value = key, value
self.prev: Optional[_Node[K, V]] = None
self.next: Optional[_Node[K, V]] = None
class _RecencyList(Generic[K, V]):
"""Doubly linked list with sentinel ends. Front = most recently used."""
def __init__(self) -> None:
self._head: _Node = _Node(None, None) # sentinels: no None checks at the ends
self._tail: _Node = _Node(None, None)
self._head.next, self._tail.prev = self._tail, self._head
def push_front(self, node: _Node[K, V]) -> None:
first = self._head.next
node.prev, node.next = self._head, first
self._head.next = first.prev = node
def unlink(self, node: _Node[K, V]) -> None:
node.prev.next, node.next.prev = node.next, node.prev
node.prev = node.next = None
def move_to_front(self, node: _Node[K, V]) -> None:
self.unlink(node)
self.push_front(node)
def pop_back(self) -> _Node[K, V]:
last = self._tail.prev
if last is self._head:
raise IndexError("pop_back on empty list")
self.unlink(last)
return last
def keys(self) -> list[K]:
out, node = [], self._head.next
while node is not self._tail:
out.append(node.key)
node = node.next
return out
class LRUCache(Generic[K, V]):
"""Fixed-size cache. Full + new key -> the least recently used entry goes."""
def __init__(self, capacity: int, on_evict: Callable[[K, V], None] | None = None) -> None:
if type(capacity) is not int or capacity < 1:
raise ValueError(f"capacity must be a positive int, got {capacity!r}")
self._capacity = capacity
self._index: dict[K, _Node[K, V]] = {} # key -> node, O(1) lookup
self._order: _RecencyList[K, V] = _RecencyList() # recency, O(1) moves
self._on_evict = on_evict
self._hits = self._misses = self._evictions = 0
def get(self, key: K, default: object = None) -> V | object:
node = self._index.get(key)
if node is None:
self._misses += 1
return default
self._hits += 1
self._order.move_to_front(node)
return node.value
def put(self, key: K, value: V) -> None:
node = self._index.get(key)
if node is not None: # update: refresh recency, never evict
node.value = value
self._order.move_to_front(node)
return
if len(self._index) == self._capacity:
self._evict()
node = _Node(key, value)
self._index[key] = node
self._order.push_front(node)
def _evict(self) -> None:
victim = self._order.pop_back()
del self._index[victim.key]
self._evictions += 1
if self._on_evict:
self._on_evict(victim.key, victim.value)
def __contains__(self, key: object) -> bool: # a peek: does NOT refresh recency
return key in self._index
def __len__(self) -> int:
return len(self._index)
def keys(self) -> list[K]:
"""Keys from most to least recently used."""
return self._order.keys()
def stats(self) -> dict[str, int]:
return {"hits": self._hits, "misses": self._misses, "evictions": self._evictions,
"size": len(self), "capacity": self._capacity}
# ── the API client that uses the cache ─────────────────────────────────
@dataclass(frozen=True)
class Product:
sku: str
name: str
price_paise: int
class FakeProductApi:
"""Stands in for a slow HTTP API; counts calls so the demo shows savings."""
def __init__(self, catalogue: dict[str, Product]) -> None:
self._catalogue = catalogue
self.calls = 0
def fetch(self, sku: str) -> Product | None:
self.calls += 1
return self._catalogue.get(sku) # None = unknown SKU (a 404)
_MISSING = object() # sentinel: tells "cached None" apart from "not cached"
class ProductClient:
"""Composition: the client HAS a cache and an API; it is neither of them."""
def __init__(self, api: FakeProductApi, cache: LRUCache[str, Product | None]) -> None:
self._api, self._cache = api, cache
def product(self, sku: str) -> Product | None:
cached = self._cache.get(sku, _MISSING)
if cached is not _MISSING:
return cached # type: ignore[return-value]
product = self._api.fetch(sku)
self._cache.put(sku, product) # 404s are cached too (negative caching)
return product
def main() -> None:
items = [("A1", "USB-C cable", 29900), ("B2", "Laptop stand", 149900),
("C3", "Webcam", 349900), ("D4", "Desk lamp", 89900)]
api = FakeProductApi({s: Product(s, n, p) for s, n, p in items})
evicted: list[str] = []
cache: LRUCache[str, Product | None] = LRUCache(3, on_evict=lambda k, v: evicted.append(k))
client = ProductClient(api, cache)
print("1) Product lookups through a 3-slot LRU cache")
for sku in ["A1", "B2", "A1", "C3", "D4", "A1", "B2", "Z9", "Z9"]:
p = client.product(sku)
print(f" {sku}: {p.name if p else 'not found':<12} api_calls={api.calls}"
f" mru->lru={cache.keys()}")
print(f" evicted in order: {evicted}")
print("2) Price update on a full cache: refresh, no eviction")
cache.put("B2", Product("B2", "Laptop stand", 139900))
print(f" B2 price={cache.get('B2').price_paise} size={len(cache)} evicted={evicted}")
print("3) 'in' is a peek: it does not save A1 from eviction")
print(f" 'A1' in cache: {'A1' in cache} mru->lru={cache.keys()}")
cache.put("E5", Product("E5", "Mouse", 59900))
print(f" after put E5: mru->lru={cache.keys()} evicted={evicted}")
print("4) Invalid capacity")
for bad in (0, 2.5):
try:
LRUCache(bad) # type: ignore[arg-type]
except ValueError as err:
print(f" {err}")
print(f"5) stats: {cache.stats()}")
if __name__ == "__main__":
main()
- Nodes store their key. Evicting the tail node needs its key to delete it from the dict.
- Update is checked first.
putlooks the key up before checking capacity, fixing the naive bug. - The caller picks the miss value.
ProductClientpasses a private_MISSINGsentinel, so a cachedNoneis a hit. inis a peek.__contains__checks membership without touching recency.- Small, fixed nodes.
_Nodeuses__slots__, which denies a per-instance__dict__and saves space.
Step 5: Run it and check the output
1) Product lookups through a 3-slot LRU cache
A1: USB-C cable api_calls=1 mru->lru=['A1']
B2: Laptop stand api_calls=2 mru->lru=['B2', 'A1']
A1: USB-C cable api_calls=2 mru->lru=['A1', 'B2']
C3: Webcam api_calls=3 mru->lru=['C3', 'A1', 'B2']
D4: Desk lamp api_calls=4 mru->lru=['D4', 'C3', 'A1']
A1: USB-C cable api_calls=4 mru->lru=['A1', 'D4', 'C3']
B2: Laptop stand api_calls=5 mru->lru=['B2', 'A1', 'D4']
Z9: not found api_calls=6 mru->lru=['Z9', 'B2', 'A1']
Z9: not found api_calls=6 mru->lru=['Z9', 'B2', 'A1']
evicted in order: ['B2', 'C3', 'D4']
2) Price update on a full cache: refresh, no eviction
B2 price=139900 size=3 evicted=['B2', 'C3', 'D4']
3) 'in' is a peek: it does not save A1 from eviction
'A1' in cache: True mru->lru=['B2', 'Z9', 'A1']
after put E5: mru->lru=['E5', 'B2', 'Z9'] evicted=['B2', 'C3', 'D4', 'A1']
4) Invalid capacity
capacity must be a positive int, got 0
capacity must be a positive int, got 2.5
5) stats: {'hits': 4, 'misses': 6, 'evictions': 4, 'size': 3, 'capacity': 3}
Tested: Python 3.13.18 — python3 main.py, 2026-11-29. Output above is copied from that run.
Adding D4 evicts B2, not A1: A1 is older but was read on the third lookup. The second Z9 costs no API call because the 404 was cached. A separate assert run (capacity 1, cached None, update order, rejecting True and "3") also passed.
Why this design works
- Single responsibility: the list splices pointers, the cache applies the policy, the client decides when to call the API.
- Encapsulation protects an invariant: every dict entry has exactly one node in the list.
- Composition keeps the API narrow: subclassing
dictwould exposeupdate()andsetdefault(), ways around eviction. - Behaviour, not type:
ProductClientworks with any object offeringgetandput, so a TTL cache can replace it.
Trade-offs, edge cases and when not to use it
We ran both classes side by side: fill to capacity, then time 20,000 random get hits (seed 42) with python3 bench.py on Python 3.13.18. Absolute numbers vary by machine.
import random, sys, time; sys.path.insert(0, ".")
from main import LRUCache
exec(open("naive.py").read().split("\nc = ")[0]) # NaiveLRU class only
for cap in (100, 1_000, 10_000, 100_000):
rng = random.Random(42); keys = [rng.randrange(cap) for _ in range(20_000)]
for name, cls in (("NaiveLRU", NaiveLRU), ("LRUCache", LRUCache)):
c = cls(cap)
for i in range(cap): c.put(i, i)
t = time.perf_counter()
for k in keys: c.get(k) # every get is a hit
ms = (time.perf_counter() - t) * 1000
print(f"capacity={cap:>7,} {name:<8} 20,000 random gets: {ms:9.1f} ms")
capacity= 100 NaiveLRU 20,000 random gets: 6.1 ms capacity= 100 LRUCache 20,000 random gets: 3.8 ms capacity= 1,000 NaiveLRU 20,000 random gets: 55.9 ms capacity= 1,000 LRUCache 20,000 random gets: 3.9 ms capacity= 10,000 NaiveLRU 20,000 random gets: 515.2 ms capacity= 10,000 LRUCache 20,000 random gets: 4.1 ms capacity=100,000 NaiveLRU 20,000 random gets: 5586.5 ms capacity=100,000 LRUCache 20,000 random gets: 6.6 ms
The naive cost grows about tenfold per tenfold capacity; the linked-list version stays almost flat.
| Option | get / put cost | Eviction hook, stats | Thread safety | Best for |
|---|---|---|---|---|
| Dict + list (naive) | O(n) | None | None | A first sketch |
| Dict + linked list (this episode) | O(1) average | on_evict, stats() |
Add a lock | Interviews, custom hooks |
collections.OrderedDict |
O(1): move_to_end, popitem(last=False) |
Build your own | Add a lock | Production Python |
functools.lru_cache |
Built in | cache_info(): hits, misses, maxsize, currsize |
Threadsafe; function may run twice on a race | Memoising functions |
Java LinkedHashMap (access order) |
Built in | Override removeEldestEntry |
Not synchronized | Production Java |
When it’s overkill: for memoising a pure function, use functools.lru_cache. In production Python, wrap an OrderedDict; its docs say it handles frequent reordering better than dict. Remember LRU only sees recency: one scan of cold keys can flush hot entries, and nothing expires on its own.
Interview follow-up questions
How would you make this LRU cache thread-safe?
Every public method needs the same lock, including get, because a read moves a node and two concurrent reads can corrupt the pointers. Create one threading.Lock in __init__ and wrap each method body in with self._lock:. Run the on_evict callback outside the lock so a slow callback can’t block readers. If the lock becomes a bottleneck, shard into N caches chosen by hash(key) % N.
How would you add a time-to-live (TTL)?
Store an expiry time in each node and inject a clock function, so tests control time instead of sleeping. On get, an expired node is unlinked, counted as an expiry and reported as a miss. That is lazy expiry: cheap, but dead entries hold their slot until touched or evicted. If memory matters, add a periodic sweep from the LRU end, where stale entries collect.
How would you support LFU or another eviction policy?
Put the “which entry goes next” decision behind an interface, as in the Strategy pattern episode. The cache calls policy.record_access(key) and policy.victim(). LRU is the linked list you already have; LFU (least frequently used) needs per-frequency buckets to stay O(1). A pluggable policy adds an indirection on every access, so add it only when you need two policies.
The same solution in Java
Same design: a HashMap to nodes plus a hand-written doubly linked list. get returns an Optional, and Optional.ofNullable(null) is empty, so cache 404s as an explicit “not found” value. In production Java, an access-ordered LinkedHashMap overriding removeEldestEntry does this job.
Show the Java version
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class Main {
public static void main(String[] args) {
LruCache<String, String> cache = new LruCache<>(3);
Map<String, String> api = Map.of("A1", "USB-C cable", "B2", "Laptop stand",
"C3", "Webcam", "D4", "Desk lamp");
int apiCalls = 0;
for (String sku : List.of("A1", "B2", "A1", "C3", "D4", "A1", "B2")) {
Optional<String> hit = cache.get(sku);
if (hit.isEmpty()) { // miss: call the "API", then cache it
apiCalls++;
cache.put(sku, api.get(sku));
}
System.out.printf("%s: %-4s api_calls=%d mru->lru=%s%n",
sku, hit.isPresent() ? "hit" : "miss", apiCalls, cache.keys());
}
cache.put("B2", "Laptop stand v2"); // update on a full cache: no eviction
System.out.println("after update: " + cache.keys() + " size=" + cache.size());
try {
new LruCache<String, String>(0);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}
/** Fixed-size cache: HashMap for O(1) lookup + doubly linked list for O(1) recency. */
final class LruCache<K, V> {
private static final class Node<K, V> {
final K key;
V value;
Node<K, V> prev, next;
Node(K key, V value) { this.key = key; this.value = value; }
}
private final int capacity;
private final Map<K, Node<K, V>> index = new HashMap<>();
private final Node<K, V> head = new Node<>(null, null); // sentinel, MRU side
private final Node<K, V> tail = new Node<>(null, null); // sentinel, LRU side
LruCache(int capacity) {
if (capacity < 1) throw new IllegalArgumentException("capacity must be >= 1, got " + capacity);
this.capacity = capacity;
head.next = tail;
tail.prev = head;
}
Optional<V> get(K key) {
Node<K, V> node = index.get(key);
if (node == null) return Optional.empty();
moveToFront(node);
return Optional.ofNullable(node.value);
}
void put(K key, V value) {
Node<K, V> node = index.get(key);
if (node != null) { node.value = value; moveToFront(node); return; }
if (index.size() == capacity) {
Node<K, V> lru = tail.prev;
unlink(lru);
index.remove(lru.key);
}
node = new Node<>(key, value);
index.put(key, node);
pushFront(node);
}
int size() { return index.size(); }
List<K> keys() {
List<K> out = new ArrayList<>();
for (Node<K, V> n = head.next; n != tail; n = n.next) out.add(n.key);
return out;
}
private void moveToFront(Node<K, V> node) { unlink(node); pushFront(node); }
private void unlink(Node<K, V> node) {
node.prev.next = node.next;
node.next.prev = node.prev;
}
private void pushFront(Node<K, V> node) {
node.prev = head;
node.next = head.next;
head.next.prev = node;
head.next = node;
}
}
A1: miss api_calls=1 mru->lru=[A1] B2: miss api_calls=2 mru->lru=[B2, A1] A1: hit api_calls=2 mru->lru=[A1, B2] C3: miss api_calls=3 mru->lru=[C3, A1, B2] D4: miss api_calls=4 mru->lru=[D4, C3, A1] A1: hit api_calls=4 mru->lru=[A1, D4, C3] B2: miss api_calls=5 mru->lru=[B2, A1, D4] after update: [B2, A1, D4] size=3 capacity must be >= 1, got 0
Tested: OpenJDK 21.0.13.1 — java Main.java, 2026-11-29. Output above is copied from that run.
Practice: extend it yourself
- Add a TTL. Add
ttl_secondsand aclockparameter. Expected behaviour: with a fake clock, agetafter the TTL is a miss, removes the entry and counts asexpired, not an eviction. - Add
resize(new_capacity). Expected behaviour: shrinking from 3 to 1 evicts the two least recently used entries, callingon_evictfor each;resize(0)raisesValueError. - Swap the engine. Rebuild
LRUCacheonOrderedDictwith the same public methods. Expected behaviour:main()prints exactly the Step 5 output.
- An O(1) LRU cache implementation pairs a hash map (key to node) with a doubly linked list (recency order).
- The
prevpointer lets a node found through the map be unlinked without a scan. - Each node stores its key so eviction can delete it from the map.
- Updating an existing key must refresh it, never evict another entry.
- A caller-chosen sentinel keeps a cached
Nonedistinct from a miss. - In production, prefer
functools.lru_cache,OrderedDictor Java’sLinkedHashMap.
Frequently Asked Questions
What is an LRU cache?
An LRU (least recently used) cache is a fixed-size store that, when full, discards the entry that has gone longest without being read or written. It suits workloads where recently used data is likely to be used again, such as popular product pages.
Why does an LRU cache use a doubly linked list instead of a singly linked list?
To unlink a node in O(1) you need its predecessor. A doubly linked node stores a prev pointer, so the node the hash map hands you can be spliced out at once. A singly linked list forces a walk from the head to find the predecessor, which is O(n).
What is the time complexity of an LRU cache implementation?
With a hash map plus a doubly linked list, get and put are O(1) on average: one hash lookup and a few pointer changes. Memory is O(capacity). Keeping keys in a Python list makes every access O(n), because list.remove scans and pop(0) shifts.
Should I use functools.lru_cache or write my own LRU cache in Python?
Use functools.lru_cache to memoise a function with hashable arguments; it reports hits and misses. Write your own class, or wrap OrderedDict, when you need a cache object you call directly, an eviction hook or per-key updates.
How do you make an LRU cache thread-safe?
Guard every public method with one lock, including get, because get moves a node and so changes shared state. In Python use a threading.Lock in a with-block. If one lock becomes a bottleneck, shard the cache by key hash.