LRU Cache
Write a class LRUCache(capacity) that stores at most capacity key-value pairs and, when full, evicts the least recently used one.
get(key)returns the value, orNoneif the key is missing. A successfulgetcounts as a use of the key.put(key, value)stores the value and counts as a use. Putting an existing key updates its value (and does not evict anything). When a new key would exceed the capacity, first remove the least recently used key.
Understand the problem
Simulate a small cache by hand.
Capacity 2. put("a", 1), put("b", 2), get("a"), put("c", 3). Which key was evicted?
After the first three calls, b is the least recently used: a was just read, so it is the newest, and b is the oldest. Adding c exceeds the capacity, so b goes.
Which standard-library structure is a dictionary that remembers insertion order and lets you move a key to the end in O(1)?
collections.dequecollections.OrderedDictcollections.Counter
OrderedDict has move_to_end(key) and popitem(last=False) (remove the oldest). Together they give O(1) "mark as used" and "evict oldest". (A normal dict also keeps order, but has no move_to_end.)
Write the solution
Write the class.
class LRUCache:
# Write your code here.
pass
Hint 1: a question to ask yourself
How can the structure itself tell you which key was used longest ago?
Hint 2: the shape of the answer
Keep an OrderedDict where the end is the most recently used. On a hit, move_to_end(key). On put, store, move_to_end(key), then while it is too big popitem(last=False).
Reflect
Solution
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity):
self.capacity = capacity
self._data = OrderedDict()
def get(self, key):
if key not in self._data:
return None
self._data.move_to_end(key)
return self._data[key]
def put(self, key, value):
self._data[key] = value
self._data.move_to_end(key)
if len(self._data) > self.capacity:
self._data.popitem(last=False)
Another way: a plain dict, which also keeps order
class LRUCache:
def __init__(self, capacity):
self.capacity = capacity
self._data = {}
def get(self, key):
if key not in self._data:
return None
value = self._data.pop(key)
self._data[key] = value
return value
def put(self, key, value):
self._data.pop(key, None)
self._data[key] = value
if len(self._data) > self.capacity:
del self._data[next(iter(self._data))]
What this tests: designing a data structure, OrderedDict, thinking about what operations must be O(1), and edge cases (updating an existing key does not evict).
The idea: a cache must find a key fast (a hash table) and know the order of use (a list). The classic design joins a dictionary and a doubly linked list. OrderedDict is exactly that, built in.
What counts as a use: reading a key (get) and writing it (put, also for an existing key). Forgetting one of them is the commonest mistake.
In real code: functools.lru_cache is an LRU cache for function results. Writing your own is the interview exercise; using the library is the production answer.
Cost: get and put are O(1).
What an interviewer might ask next: Add an expiry time to each entry (a TTL). How does it change get? (Check the age; if too old, delete and return None.)
VISIBLE = 3
CASES = [
('c = LRUCache(2)\nc.put("a", 1)\nc.put("b", 2)\nc.get("a")\nc.put("c", 3)\nresult = (c.get("b"), c.get("a"), c.get("c"))', (None, 1, 3), 'a read protects a key from eviction'),
('c = LRUCache(1)\nc.put("a", 1)\nc.put("b", 2)\nresult = (c.get("a"), c.get("b"))', (None, 2), 'capacity one'),
('c = LRUCache(2)\nresult = c.get("x")', None, 'a missing key'),
('c = LRUCache(2)\nc.put("a", 1)\nc.put("a", 10)\nresult = c.get("a")', 10, 'updating a key'),
('c = LRUCache(2)\nc.put("a", 1)\nc.put("b", 2)\nc.put("a", 5)\nc.put("c", 3)\nresult = (c.get("a"), c.get("b"), c.get("c"))', (5, None, 3), 'an update counts as a use'),
('c = LRUCache(2)\nc.put("a", 1)\nc.put("b", 2)\nc.put("a", 9)\nresult = (c.get("a"), c.get("b"))', (9, 2), 'updating an existing key evicts nothing'),
('c = LRUCache(3)\nfor k in "abcd":\n c.put(k, k.upper())\nresult = [c.get(k) for k in "abcd"]', [None, 'B', 'C', 'D'], 'the oldest of four is evicted'),
('c = LRUCache(2)\nc.put("a", 0)\nresult = c.get("a")', 0, 'a falsy value is a value'),
('c = LRUCache(2)\nc.put("a", 1)\nc.put("b", 2)\nc.get("a")\nc.get("b")\nc.put("c", 3)\nresult = (c.get("a"), c.get("b"))', (None, 2), 'the least recently read key is evicted'),
]