AAI Agentic Handbook
Problem 67 · Object & System Design

LRU Cache from Scratch

MediumClassic DSA & systems
01Problem

Implement an LRU cache with get(key) and put(key, value) in O(1), evicting the least-recently-used entry when capacity is exceeded. Do not use OrderedDict.

02Key insight

Hash map gives O(1) lookup to a node; a doubly linked list with sentinel head/tail gives O(1) move-to-front and evict-from-tail. Sentinels eliminate all null-edge cases.

03Solution

Try it first.

TimeO(1) per op
SpaceO(capacity)
tests.py · 3 passing
tests.pypython7 lines
c = LRUCache(2)
c.put(1, 1); c.put(2, 2)
assert c.get(1) == 1
c.put(3, 3)
assert c.get(2) == -1
c.put(1, 10); c.put(4, 4)
assert c.get(3) == -1 and c.get(1) == 10 and c.get(4) == 4
04Staff-level follow-up

Make it thread-safe at high QPS? Shard into N independent LRUs by key hash, each with its own lock (or use CLOCK/approximate LRU like Redis sampling to avoid list mutation on every read).