Replay Bounded Cache Commands with Recency Eviction
Data Structure DesignAuto-graded · 18 test casesLast updated
Simulate a fixed-capacity key-value store that evicts its stalest entry, replaying a command log in O(1) per step using a hash map and recency ordering.
Bounded Cache Replay
You are given a small in-memory store that holds at most capacity integer key/value pairs. When it is full and a brand-new key arrives, the store throws out the entry that has gone unused for the longest time.
Your job is to replay a log of commands against an initially empty store and report what each command produced.
Commands
Each command is a string in operations, and the entry at the same index in arguments holds its parameters.
"get"witharguments[i] = [key]- If
keyis in the store, the result is its stored value, and the key now counts as the most recently used. - If
keyis absent, the result is-1and the store does not change.
- If
"put"witharguments[i] = [key, value]- If
keyis already in the store, overwrite its value and mark it as the most recently used. Nothing is evicted. - Otherwise, if the store already holds
capacityentries, first remove the least recently used entry, then insert the new pair as the most recently used. - The result of a
putisNone.
- If
An entry is "used" whenever it is read by a successful get or written by a put. A get on a missing key does not count as a use of anything.
Output
Return a list with one element per recognized command, in order: the retrieved value (or -1) for each get, and None for each put. A command whose name is neither "get" nor "put" is skipped and contributes nothing to the output.
Stored values can be 0, so be careful to test for key presence rather than value truthiness.
Constraints
1 <= capacity <= 100,0000 <= key <= 1,000,0000 <= value <= 1,000,000,000operationsandargumentshave the same length.- Each command should be processed in
O(1)average time.
Examples
Example 1
Input: replay_bounded_cache(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 2
Input: replay_bounded_cache(1, ['put', 'put', 'get', 'put', 'get'], [[1, 10], [1, 20], [1], [2, 30], [1]])
Output: [None, None, 20, None, -1]
Example 3
Input: replay_bounded_cache(2, ['get', 'put', 'get', 'put', 'put', 'get', 'get'], [[1], [1, 100], [1], [2, 200], [3, 300], [1], [2]])
Output: [-1, None, 100, None, None, -1, 200]
Hints
Hint 1
You need to look up a key instantly and also know which key was touched longest ago. One structure rarely does both well, so consider pairing two.
Hint 2
A hash map from key to a node in a doubly linked list lets you move a node to the 'most recent' end and drop the 'least recent' end in constant time. Dummy head and tail nodes remove edge cases.
Hint 3
Check whether the key already exists before checking whether the store is full: overwriting an existing key must never evict anything. Also, a successful get must refresh recency.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Two things must be fast at once:
- Finding an entry by key, which a hash map does in O(1) average.
- Moving an entry to the "most recent" position and removing the "least recent" one, which a doubly linked list does in O(1).
Python's OrderedDict is exactly this combination internally: a hash map plus a doubly linked list that remembers insertion order. We keep the entries ordered from least recently used (front) to most recently used (back).
For each command:
- get: if the key is present, pop it and re-insert it at the back (refreshing recency) and report its value. If absent, report
-1and change nothing. - put:
- If the key exists, remove it and re-insert it with the new value at the back. No eviction occurs.
- Otherwise, if the store already has
capacityentries, remove the front entry (the least recently used), then insert the new pair at the back. - Report
None.
- Any other command name is ignored and adds nothing to the output.
Why it is correct
Invariant: the ordered dictionary contains exactly the live keys, ordered by time of last use, oldest first. Every successful get and every put moves the touched key to the back, so the front is always the entry whose last use is the oldest, which is the one that must be evicted. Eviction happens only when inserting a new key into a full store, so the size never exceeds capacity, and overwriting an existing key never evicts. A failed get does not alter the order, as specified. Presence is tested with in, so a stored value of 0 is handled correctly.
Complexity
- Time: O(1) average per command, O(n) for n commands.
- Space: O(capacity) for the store plus O(n) for the output.
Reference solution
from collections import OrderedDict
from typing import List, Optional
def replay_bounded_cache(capacity: int, operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]:
store = OrderedDict() # least recently used first, most recently used last
result: List[Optional[int]] = []
for op, args in zip(operations, arguments):
if op == "get":
key = args[0]
if key in store:
value = store.pop(key)
store[key] = value
result.append(value)
else:
result.append(-1)
elif op == "put":
key, value = args
if key in store:
store.pop(key)
elif len(store) == capacity:
store.popitem(last=False)
store[key] = value
result.append(None)
return result
If you are asked to avoid OrderedDict, implement the same idea by hand: a dictionary from key to node, plus a doubly linked list with dummy head and tail nodes and two helpers (unlink and push_front). Each node stores its own key so that, on eviction, you can delete the matching dictionary entry.