Replay Operations on a Bounded Recency-Evicting Store
Data Structure DesignAuto-graded · 19 test casesLast updated
Simulate a fixed-size key-value store that evicts the stalest entry, replaying a list of get/put commands and returning each command's result.
Replaying Commands on a Bounded Store
You are given a store that holds at most capacity integer key-value pairs. When it runs out of room, it discards the entry that was touched longest ago. Instead of building a class, you must write a function that replays a whole list of commands against one fresh, initially empty store and reports what each command returned.
Commands
Each command is one of two kinds:
"get"with arguments[key]: look upkey.- If the key is present, return its value and treat the key as just used.
- If the key is absent, return
-1. This changes nothing in the store.
"put"with arguments[key, value]: storevalueunderkey.- If the key is already present, replace its value and treat the key as just used. Nothing is evicted.
- If the key is new and the store already holds
capacityentries, first remove the least recently used entry, then insert the new key as just used. - If the key is new and there is room, simply insert it as just used.
- A
putreturnsNone.
"Recently used" means the most recent successful get or any put on that key. A get that misses does not count as using anything.
Input
capacity: the maximum number of entries the store may hold.operations: a list of strings, each"get"or"put".arguments: a list of the same length asoperations;arguments[i]is[key]for agetand[key, value]for aput.
Output
Return a list with exactly one element per command, in order: the retrieved value or -1 for a get, and None for a put.
Each command should run in O(1) average time.
Constraints
capacity >= 1len(operations) == len(arguments)- Keys and values are integers.
- Every
operations[i]is either"get"or"put", and itsarguments[i]has the matching length. - A stored value of
-1is indistinguishable from a miss; this is expected. - Each operation should take O(1) average time.
Examples
Example 1
Input: replay_bounded_store(2, ['put', 'put', 'get', 'put', 'get', 'get'], [[1, 1], [2, 2], [1], [3, 3], [2], [3]])
Output: [None, None, 1, None, -1, 3]
Example 2
Input: replay_bounded_store(2, ['put', 'put', 'get', 'put', 'get', 'put', 'get', 'get', 'get'], [[1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]])
Output: [None, None, 1, None, -1, None, -1, 3, 4]
Example 3
Input: replay_bounded_store(1, ['put', 'get', 'put', 'get'], [[10, 7], [10], [20, 8], [10]])
Output: [None, 7, None, -1]
Hints
Hint 1
You need two abilities at once: find an entry by key instantly, and know which entry is the stalest instantly. Think about which structures give each.
Hint 2
Keep entries ordered from least to most recently used. Every successful get and every put must move that key to the 'most recent' end, and eviction removes from the other end.
Hint 3
Be careful with a put on a key that already exists while the store is full: it must refresh the key and overwrite the value without evicting anything. Python's OrderedDict (pop then reinsert, popitem(last=False)) or a hash map plus doubly linked list both work.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The store needs two things in constant time:
- Finding an entry by key, which a hash map provides.
- Maintaining usage order, so that any key can be moved to the "most recent" end and the "least recent" entry can be removed. A doubly linked list provides this.
Python's collections.OrderedDict combines both: a hash map over a doubly linked list of insertion order. We keep the invariant that the dictionary's order equals recency order, with the front being the least recently used key and the back the most recently used.
For each command:
- get: if the key is missing, output
-1and change nothing. Otherwise pop the key and reinsert it (moving it to the back), and output its value. - put:
- If the key exists, pop it so it can be reinserted at the back with the new value. The size does not grow, so no eviction happens.
- Otherwise, if the store is at capacity, remove the front entry with
popitem(last=False). - Insert the key at the back and output
None.
Why it is correct
- A successful
getand everyputcount as a use, and each moves the key to the back, so the invariant holds. - A missed
getuses no key, so leaving the order untouched is right. - Eviction only happens for a new key when the store is full, and by the invariant the front entry is the least recently used one.
- Updating an existing key never evicts, which avoids wrongly dropping an unrelated entry. Popping before reinserting is necessary because plain assignment on an
OrderedDictkeeps the old position. - The size never exceeds
capacity, since the only growing insertion is guarded by the eviction check.
Complexity
- Time: O(1) average per command, so O(n) for n commands.
- Space: O(capacity) for the store plus O(n) for the result list.
Reference solution
from collections import OrderedDict
from typing import List, Optional
def replay_bounded_store(capacity: int, operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]:
store = OrderedDict() # front = least recently used, back = most recently used
results = []
for operation, args in zip(operations, arguments):
if operation == "get":
key = args[0]
if key not in store:
results.append(-1)
else:
value = store.pop(key)
store[key] = value
results.append(value)
elif operation == "put":
key, value = args
if key in store:
store.pop(key)
elif len(store) == capacity:
store.popitem(last=False)
store[key] = value
results.append(None)
return results