Replay a Recency-Evicting Cache from a Command Log
Data Structure DesignAuto-graded · 18 test casesLast updated
Simulate a fixed-size cache that evicts the least recently used entry, by replaying text commands and collecting the answers to lookups in order.
Replay a Recency-Evicting Cache from a Command Log
A small cache stores integer keys mapped to integer values. It can hold at most capacity entries. When it overflows, it discards the entry that was used least recently.
You are given the cache size and a list of text commands. Replay the commands in order and report what each lookup returns.
Commands
Each command is a string in one of these two forms:
"PUT key value"storesvalueunderkey.- If
keyis already present, its value is overwritten and it becomes the most recently used entry. No new entry is created. - If
keyis new, it is added as the most recently used entry. If the cache now holds more thancapacityentries, the least recently used entry is removed.
- If
"GET key"looks upkey.- If present, record its value and mark the key as the most recently used.
- If absent, record
-1. A missing key changes nothing, including recency order.
An entry is "used" whenever it is written by a PUT or successfully read by a GET.
Task
Implement process_lru(capacity, operations). Return a list containing the recorded result of every GET command, in the order the GETs appear. If there are no GET commands, return an empty list.
Note that a stored value of -1 looks identical to a miss in the output. Do not treat this specially.
Constraints
1 <= capacity <= 1000000 <= len(operations) <= 200000- Keys and values are integers in the range
[-10^9, 10^9](they may be negative). - Every command matches one of the two formats above, with single spaces between tokens.
Examples
Example 1
Input: process_lru(2, ['PUT 1 10', 'PUT 2 20', 'GET 1', 'PUT 3 30', 'GET 2', 'GET 3'])
Output: [10, -1, 30]
Example 2
Input: process_lru(1, ['PUT 7 4', 'PUT 7 9', 'GET 7', 'PUT 8 5', 'GET 7', 'GET 8'])
Output: [9, -1, 5]
Hints
Hint 1
Two things must be fast: finding a key, and finding which key was used longest ago. Think about what structure gives you both.
Hint 2
Keep the keys in an ordering from least to most recently used. Each PUT and each successful GET moves its key to the recent end; eviction removes from the old end.
Hint 3
Python's OrderedDict supports moving a key to the end and popping from the front in O(1). Remember to evict only after inserting, and only when size exceeds capacity; also make sure a miss changes nothing.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
We need three fast operations: find a key, mark a key as most recently used, and remove the least recently used key. A hash map alone cannot find the oldest key quickly, and a plain list cannot find an arbitrary key quickly. Combining a hash map with an ordering of keys solves both. Python's OrderedDict is exactly this: a hash map that remembers order, with O(1) deletion of any key and O(1) removal from the front.
We keep the front of the OrderedDict as the least recently used end and the back as the most recently used end.
- PUT: if the key exists, delete it first. Then insert it with the new value, which places it at the back. If the size now exceeds
capacity, pop the front entry. - GET: on a miss, append
-1and change nothing. On a hit, remove the key and re-insert it (moving it to the back), then append its value.
Why it is correct
Invariant: the key order in the cache, front to back, matches the order of most recent use.
- It holds trivially for an empty cache.
- A PUT or a successful GET moves its key to the back and leaves the relative order of all other keys unchanged.
- A miss mutates nothing, so recency is untouched, as required.
- Eviction happens only right after an insertion pushes the size to
capacity + 1. Updating an existing key never grows the cache, so it never evicts. The newly inserted key is at the back, so the front is always a different, older key (even whencapacity == 1), and it is the true least recently used entry.
Complexity
- Time: O(n) for n commands, with O(1) cache work per command (plus the cost of parsing each short string).
- Space: O(min(capacity, n)) for the cache, plus O(g) for the output, where g is the number of GETs.
Reference solution
from collections import OrderedDict
from typing import List
def process_lru(capacity: int, operations: List[str]) -> List[int]:
cache = OrderedDict() # front = least recently used, back = most recently used
result = []
for operation in operations:
parts = operation.split()
if parts[0] == "PUT":
key = int(parts[1])
value = int(parts[2])
if key in cache:
del cache[key]
cache[key] = value
if len(cache) > capacity:
cache.popitem(last=False)
else:
key = int(parts[1])
if key not in cache:
result.append(-1)
else:
value = cache.pop(key)
cache[key] = value
result.append(value)
return result