Algorithms · Design a tiny system

LRU Cache

A cache that forgets whatever was used longest ago.

The problem

Build a cache with room for capacity items. get(key) returns the value (or -1), put(key, value) stores it, and when the cache is full it forgets the least recently used item. Both must be fast.

2[1, -1, -1, 3, 4]
1[-1, 2]
Design a tiny system. Pick the right container. The books on your desk vs. the library: keep what you use close at hand.

Start with the way that works

This version is correct. It is also the slow one. Read it first: the fast way is easier to find once you can see what the slow way wastes.

class LRUCache:a cache that forgets the least recently used item
def __init__(self, capacity):created with a size limit
self.capacity = capacityhow many items fit
self.data = {}key → value
self.order = []keys, least recently used first
def get(self, key):read a key
if key not in self.data:not in the cache?
return -1LeetCode's "missing" answer
self.order.remove(key)find the key in the line (a hidden scan!)
self.order.append(key)move it to the back: just used
return self.data[key]its value
def put(self, key, value):store a key
if key in self.data:already there?
self.order.remove(key)take it out of the line (another scan)
elif len(self.data) == self.capacity:full?
oldest = self.order.pop(0)the least recently used key (shuffles everything)
del self.data[oldest]forget it
self.data[key] = valuestore the value
self.order.append(key)it's the most recent now

Now ask: what if there were a billion?

Every big website has an LRU-style cache in front of its database. Redis, used by millions of apps, doesn’t track exact order (too much memory); it samples a few keys and evicts the oldest of them.

Aim for O(n)🔥 boss

Think it through

When the cache is full, which item goes?

  • The oldest one added
  • The one used longest ago
Show the answer

The one used longest ago. Using an item (get or put) makes it fresh again. So you need the items in order of last use, and must move one to the front when it’s used.

What gives you both a lookup by key and an order you can change in one step?

  • A list of keys
  • A dictionary plus a linked list (Python: OrderedDict)
Show the answer

A dictionary plus a linked list (Python: OrderedDict). The dictionary finds an item; the linked list moves it to the end or drops the oldest in one step. Two structures working together: browser caches, CDNs and Redis all do this.

Stuck? 3 nudges, smallest first
  1. list.remove and list.pop(0) both look harmless but walk the whole line of keys.
  2. You need a dictionary that also remembers order and can move a key to the end in one step.
  3. Python’s OrderedDict has move_to_end(key) and popitem(last=False). (Underneath it’s a dict plus a doubly linked list.)

The fast way

Try it yourself before you open this. The slow version above already passes every test, so you can change it one step at a time.

Show the fast version
from collections import OrderedDicta dict that remembers order and can reorder in one step
class LRUCache:a cache that forgets the least recently used item
def __init__(self, capacity):created with a size limit
self.capacity = capacityhow many items fit
self.data = OrderedDict()key → value, least recently used first
def get(self, key):read a key
if key not in self.data:not in the cache?
return -1LeetCode's "missing" answer
self.data.move_to_end(key)just used: move it to the back, in one step
return self.data[key]its value
def put(self, key, value):store a key
if key in self.data:already there?
self.data.move_to_end(key)it's the most recent now
self.data[key] = valuestore the value
if len(self.data) > self.capacity:too many?
self.data.popitem(last=False)forget the least recently used, in one step

Where it’s used for real

Solve it yourself.

It runs right in the page: the tests, the gremlins that try to break it, and a race up to a billion. Free, nothing to install.

More with design a tiny system