Sub topic 3
Why get and put must be O(1)
This chapter assumes you know Python classes and dictionaries, Big-O notation, and that a dictionary gives average O(1) lookup. It explains the speed target for the LRU cache and shows what goes wrong without it.
The cost of a cache operation
A cache exists to make repeated reads cheaper than recomputing a value or fetching it from a slow source. If the cache's own bookkeeping is slow, it loses that benefit. A cache of 100,000 entries that scans a list on every read is doing 100,000 steps of work just to save one database call.
An LRU cache must do two things on every call:
get(key)finds the value and marks that key as most recently used.put(key, value)stores the value, marks it as most recently used, and evicts the least recently used key if the cache is over capacity.
The target is O(1) average time for both. "O(1)" means the work does not grow as the number of stored entries grows.
The hidden work in each operation
Looking up a value is only part of the job. Each call also changes the recency order.
| Operation | Lookup | Reorder | Eviction |
|---|---|---|---|
| `get` hit | find the key | move it to most recent | none |
| `put` existing key | find the key | move it to most recent | none |
| `put` new key at capacity | check the key is absent | insert as most recent | remove least recent |
Each cell in this table must be O(1), or the whole operation is not.
A naive version that fails the target
A dictionary gives O(1) lookup. A list can track order. The obvious design combines them:
import time
class NaiveLRUCache:
def __init__(self, capacity):
self.capacity = capacity
self.data = {}
self.order = [] # least recent first
def get(self, key):
if key not in self.data:
return None
self.order.remove(key) # O(n): scan, then shift
self.order.append(key)
return self.data[key]
def put(self, key, value):
if key in self.data:
self.order.remove(key) # O(n)
elif len(self.data) >= self.capacity:
oldest = self.order.pop(0) # O(n): shifts every element
del self.data[oldest]
self.data[key] = value
self.order.append(key)
for size in (10_000, 100_000, 1_000_000):
cache = NaiveLRUCache(size)
for i in range(size):
cache.put(i, i)
start = time.perf_counter()
for i in range(1000):
cache.get(i)
elapsed = time.perf_counter() - start
print(f"capacity {size:>9}: {elapsed:.4f}s for 1000 gets")The output is correct, but the time for 1000 gets rises as the capacity rises. Exact numbers depend on your machine. The trend is the point: remove and pop(0) both touch up to n elements.
What the structure must provide
The failure shows what a better design needs:
- Find any entry by key without scanning. A hash map does this.
- Move an entry that sits anywhere in the order to the "most recent" end without shifting other entries.
- Remove the least recent entry from the other end without shifting other entries.
A hash map gives requirement 1 but keeps no order. A list gives order but needs a scan to find an entry. The next chapters look at each structure's strengths and weaknesses, then combine them.
Exercise
In NaiveLRUCache, which two lines make put and get O(n), and what does each one do that a constant-time design must avoid?
Show answer
self.order.remove(key) scans the list to find the key and then shifts the elements after it. self.order.pop(0) removes the first element and shifts every remaining element left. A constant-time design must reorder and evict without searching for the entry and without shifting other entries.