Sub topic 2
The Least-Recently-Used Policy
This chapter assumes you know basic Python classes and dictionaries, and that you can read Big-O notation. It covers what the LRU policy decides and which operations a cache must support to apply it. The data structures come in later chapters.
What the policy decides
A cache has a fixed capacity. When it is full and a new entry arrives, the cache must remove one existing entry. An eviction policy is the rule that picks the entry to remove.
The least-recently-used (LRU) policy removes the entry that has gone unused for the longest time. It rests on temporal locality: data used recently is likely to be used again soon, and data untouched for a long time is less likely to be needed.
"Used" means two things:
- A read of the key through
get. - A write to the key through
put, whether the key is new or already present.
Both actions make that key the most recently used entry.
Recency, not frequency
LRU tracks when a key was last touched. It does not track how many times. A key read 100 times last week loses to a key read once a minute ago. Policies that count accesses are a different family, called least-frequently-used (LFU).
The operations the cache needs
To apply the policy, the cache exposes two operations:
| Operation | Behavior | Effect on recency |
|---|---|---|
| `get(key)` | Returns the value, or `None` if the key is absent | A hit makes the key most recent. A miss changes nothing. |
| `put(key, value)` | Stores the value | The key becomes most recent. If the key is new and the cache is full, the least recent entry is evicted first. |
Internally the cache must be able to do four things:
- Find an entry by key.
- Move an entry to the "most recent" position.
- Identify the "least recent" entry.
- Remove an entry.
A worked trace
Take a cache with capacity 3. The lists show entries from most recent to least recent.
put("a", 1)gives[a].put("b", 2)gives[b, a].put("c", 3)gives[c, b, a]. The cache is now full.get("a")returns 1 and gives[a, c, b]. Keyamoved to the front.put("d", 4)must evict. The least recent entry isb, so the result is[d, a, c].
Key a was the oldest insertion, yet it survived. The get in step 4 renewed it. LRU judges by last use, not by insertion order. Eviction by insertion order is FIFO, a different policy.
A naive version and its cost
You can implement the policy directly with a Python list that keeps keys in recency order:
class SlowLRUCache:
def __init__(self, capacity):
if capacity <= 0:
raise ValueError("capacity must be positive")
self.capacity = capacity
self.values = {}
self.order = [] # least recent first, most recent last
def get(self, key):
if key not in self.values:
return None
self.order.remove(key) # O(n) scan
self.order.append(key)
return self.values[key]
def put(self, key, value):
if key in self.values:
self.order.remove(key) # O(n) scan
elif len(self.values) >= self.capacity:
oldest = self.order.pop(0) # O(n) shift
del self.values[oldest]
self.values[key] = value
self.order.append(key)
cache = SlowLRUCache(3)
cache.put("a", 1)
cache.put("b", 2)
cache.put("c", 3)
print(cache.get("a")) # 1
cache.put("d", 4) # evicts "b"
print(cache.get("b")) # None
print(cache.get("a")) # 1This version is correct and follows the policy exactly. But list.remove scans the list and pop(0) shifts every remaining element, so each operation costs O(n). The next chapter explains why that cost matters and what target to aim for.
Common mistakes
- Treating a
getmiss as a use. A miss touches no entry, so recency must not change. - Forgetting that
puton an existing key also refreshes recency. - Evicting when updating an existing key. An update does not grow the cache, so nothing should be removed.
Exercise
A cache with capacity 2 receives these calls in order: put(1, "a"), put(2, "b"), put(1, "z"), put(3, "c"). Which keys remain, and why?
Show answer
Keys 1 and 3 remain. The call put(1, "z") updates an existing key, so nothing is evicted and key 1 becomes most recent, giving the order [1, 2]. Then put(3, "c") adds a new key to a full cache, so the least recent key, 2, is evicted. The final order is [3, 1].
Exercise
Why is LRU not the same as evicting the oldest inserted entry?
Show answer
LRU ranks entries by last use, and both get and put count as use. An entry inserted early but read recently stays near the front, while insertion-order eviction (FIFO) would remove it anyway.