LRU and LFU caches
An LRU cache evicts the least recently used item. A hash map plus a doubly linked list gives O(1) get and put. LFU evicts the least frequently used.
Before you start: Hash tables with separate chaining.
The idea
A browser keeps 3 pages in a small fast cache. When a 4th page arrives, which page should leave?
A cache is small, fast storage for recent data. When it is full, a new item must replace an old one.
Intuition
Keep keys in order of last use. Key 2 was used last and sits at the front, while key 1 at the tail leaves first.
LRU means least recently used. A key used a moment ago will likely be used again soon.
The map stores, for each key, its list node: key 3 jumps straight to node 3:30. The node's prev and next links let it leave the list in O(1).
A list alone needs a scan to find a key. A map alone has no order. Together each operation is O(1).
Complexity
get and put each cost O(1): one map lookup and a few link changes. Space is O(capacity).
JavaScript's Map and Python's OrderedDict keep a linked list of keys inside, so the short code has the same costs.
Pitfalls
get must move its key to the front too. Here get 2 skipped the move, so 2 is evicted next.
put on a cached key updates that node and moves it. Adding a new node leaves a stale copy of 1.
Variations
LFU evicts the key with the fewest uses, not the oldest. Key 2 has 1 use, so it goes first.
LFU keeps a use count per key. A tie goes to the least recent key. Operating systems pick pages to evict the same way.
Code
Pseudocode
map ← empty; list ← empty doubly linked list
get(key):
if key not in map: return -1
node ← map[key]
move node to the front of list
return node.value
put(key, value):
if key in map
map[key].value ← value; move map[key] to the front
else
if size = capacity
tail ← remove the last node of list; delete map[tail.key]
map[key] ← new node (key, value) at the front of list
Python
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity):
self.cap = capacity
self.data = OrderedDict()
def get(self, key):
if key not in self.data:
return -1
self.data.move_to_end(key)
return self.data[key]
def put(self, key, value):
if key in self.data:
self.data[key] = value
self.data.move_to_end(key)
else:
if len(self.data) == self.cap:
self.data.popitem(last=False)
self.data[key] = value
JavaScript
class LRUCache {
constructor(capacity) {
this.cap = capacity;
this.map = new Map();
}
get(key) {
if (!this.map.has(key)) return -1;
const value = this.map.get(key);
this.map.delete(key);
this.map.set(key, value);
return value;
}
put(key, value) {
if (this.map.has(key)) this.map.delete(key);
else if (this.map.size === this.cap) {
this.map.delete(this.map.keys().next().value);
}
this.map.set(key, value);
}
}
Cost at a glance
| Access | get O(1) |
|---|---|
| Search | O(1) |
| Insert | put O(1) |
| Delete | evict O(1) |
| Space | O(capacity) |
Practice problems (6)
Choose the structures Warm-up
An LRU cache needs get and put in O(1). Each must find a key, move it to the most recent end, and evict the least recently used key when full. Which pair of structures does that?
Count cache misses Warm-up
An LRU cache holds up to capacity keys and starts empty. The keys in keys are accessed in order. An access is a hit when the key is cached, and it becomes the most recent key. Otherwise it is a miss: the key is loaded, and if the cache is full, the least recently used key is evicted first.
Return the number of misses.
Predict evictions Standard
Follow an LRU cache with capacity 2 through these commands: put 1 1, put 2 2, get 1, put 3 3, get 2, put 4 4, get 1, get 3, get 4. Answer each question before the step plays.
LRU cache Standard
Simulate an LRU cache that holds up to capacity keys and starts empty. Run the commands in order:
get Kreturns the value of key K, or-1if K is not cached. A hit makes K the most recently used key.put K Vstores V under K and makes K the most recently used key. If K is new and the cache is full, first evict the least recently used key.
Return the results of the get commands in order. Each command must take O(1) on average.
Spot the bug: get forgets the order Standard
This LRU cache runs get K and put K V commands and returns the get results. The map keeps keys in insertion order, so its first key is the least recently used. It gives wrong answers for some inputs. Click the line with the bug, then fix it.
LFU cache Challenge
Simulate an LFU (least frequently used) cache that holds up to capacity keys and starts empty. Each cached key counts its uses. A get hit or a put adds one use, and a new key starts with 1 use. Run the commands in order:
get Kreturns the value of K, or-1if K is not cached.put K Vstores V under K. If K is new and the cache is full, first evict the key with the fewest uses. On a tie, evict the least recently used of those keys.
Return the results of the get commands in order. Each command must take O(1) on average.
Next on the path: CPU scheduling: FCFS, SJF, priority, round robin