827. Build an LRU cache for model responses
Why it matters LRU caches front LLM endpoints, embedding services and KV block managers, and the problem is a staple of coding interviews.
An LRU (least recently used) cache keeps the most recently used responses and evicts the one untouched for longest when it is full. It is one of the most asked coding interview problems and sits in front of many LLM endpoints.
Write run_lru(capacity, ops). ops is a list of ("put", key, value) or ("get", key). A get returns the value or None and marks the key as most recently used. A put inserts or updates the key, marks it most recently used, and if the cache now holds more than capacity keys, evicts the least recently used one. Return the list of results of the get operations in order. Every operation must be O(1) on average.
def run_lru(capacity, ops)Example 1
Input: run_lru(2, [('put', 'a', 1), ('put', 'b', 2), ('get', 'a'), ('put', 'c', 3), ('get', 'b'), ('get', 'c')])
Output: [1, None, 3]
Example 2
Input: capacity = 1, ops = [('put', 1, 'x'), ('put', 1, 'y'), ('get', 1)]
Output: ['y']
Example 3
Input: capacity = 2, ops = [('put', 1, 1), ('put', 2, 2), ('put', 1, 10), ('put', 3, 3), ('get', 2), ('get', 1)]
Output: [None, 10]
Constraints
- Python 3 standard library. Code runs in your browser.
- Your code must pass all 5 tests to be accepted.
Hint 1
A dict alone cannot tell you which key is oldest; you also need an order.
Hint 2
OrderedDict.move_to_end and popitem(last=False) are both O(1).
Hint 3
Updating an existing key also counts as a use.
Common mistakes
- Scanning a list to find the oldest key, which is O(n) per operation and too slow for 100,000 puts.
- Forgetting that get also refreshes the key's position.
Understand the idea
You need fast lookup (a hash map) and fast reordering (a doubly linked list). Python's OrderedDict is both: move_to_end marks use and popitem(last=False) removes the oldest.
capacity 2, put a, put b, get a (a is now newest), put c evicts b, so get b is None and get c is 3.
get and put both move the key to the end; evict from the front when over capacity