Replay Operations Against an LRU Cache
Data Structure DesignAuto-graded · 19 test casesLast updated
Replay a scripted sequence of get/put operations against a fixed-capacity LRU cache and return one result per operation.
You are asked to implement an in-memory cache that holds key/value pairs and discards entries by least-recently-used (LRU) order once it is full.
Instead of building an object with the usual method calls, you will write a single function that replays a scripted list of operations and reports what each one produced.
The function receives:
capacity: a positive integer, the maximum number of keys the cache may hold.operations: a list where each entry is the string"get"or"put".arguments: a parallel list of argument lists. An entry paired with"get"is[key]; an entry paired with"put"is[key, value].
For each operation, in order:
"get"with[key]: ifkeyis present, return its stored value and treatkeyas the most recently used. Ifkeyis absent, produce-1and leave the recency order untouched."put"with[key, value]: insert or replacekeywithvalue, and treatkeyas the most recently used. If this inserts a new key and the number of stored keys now exceedscapacity, remove the least-recently-used key. Replacing the value of an existing key never changes the key count and so never evicts.
Build a result list with exactly one item per operation, in the same order: the produced value (-1 for a miss) for each "get", and None for each "put". Return this list.
Constraints
1 <= capacity <= 10001 <= len(operations) == len(arguments) <= 1000- Every entry of
operationsis exactly"get"or"put". "get"entries ofargumentshave length 1;"put"entries have length 2.0 <= key <= 10^4-10^4 <= value <= 10^4- The returned list has the same length as
operations.
Examples
Example 1
Input: simulate_fixed_capacity_cache(2, ['put', 'put', 'get', 'put', 'get', 'get', 'put', 'get'], [[1, 10], [2, 20], [1], [3, 30], [2], [3], [1, 15], [1]])
Output: [None, None, 10, None, -1, 30, None, 15]
Example 2
Input: simulate_fixed_capacity_cache(1, ['get', 'put', 'get', 'put', 'put', 'get'], [[5], [5, 50], [5], [6, 60], [7, 70], [6]])
Output: [-1, None, 50, None, None, -1]
Example 3
Input: simulate_fixed_capacity_cache(2, ['put', 'put', 'put', 'get', 'get', 'get'], [[1, 1], [1, 2], [2, 3], [1], [2], [3]])
Output: [None, None, None, 2, 3, -1]
Hints
Hint 1
Record the result of every operation in order; puts contribute None, gets contribute the value or -1.
Hint 2
Track recency with a dict whose insertion order you can reorder: remove and re-insert a key to mark it as freshly used.
Hint 3
Do the eviction check only after inserting a brand-new key, never after an update of an existing one.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Simulate the cache over the operation list, keeping a single structure that remembers both values and recency order. Python's OrderedDict keeps keys in the order they were inserted, and it lets us delete a key and re-add it cheaply so that the key moves to the end (the most-recently-used position).
For each operation:
get: if the key is present, remove it and re-insert it (moving it to the MRU end), then record its value. If absent, record-1and change nothing.put: if the key already exists, remove it first so the re-insert lands at the MRU end. Then set the value. Finally, if the cache size exceedscapacity, drop the first (least-recently-used) key. RecordNone.
Collect one output entry per operation into a result list.
Why It Is Correct
The OrderedDict key order always reflects last-use time: any successful get or any put (new or update) re-inserts the key at the end, so the front is always the key whose last use is oldest. Eviction happens only when a new key pushes the count to capacity + 1, and the just-inserted key sits at the end, so popitem(last=False) always removes the genuinely least-recently-used key. Updates never change the count, so they never trigger eviction.
Complexity
- Time: O(1) amortized per operation.
- Space: O(capacity) for the cache, O(number of operations) for the output.
from collections import OrderedDict
from typing import List, Optional
def simulate_fixed_capacity_cache(capacity: int, operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]:
cache = OrderedDict()
output = []
for op, args in zip(operations, arguments):
if op == "get":
key = args[0]
if key in cache:
val = cache.pop(key)
cache[key] = val
output.append(val)
else:
output.append(-1)
else:
key, val = args
if key in cache:
cache.pop(key)
cache[key] = val
if len(cache) > capacity:
cache.popitem(last=False)
output.append(None)
return output