Replay a Bounded Recency Store from an Operation Log
Data Structure DesignAuto-graded · 16 test casesLast updated
Simulate a fixed-size key-value store that discards the least recently touched entry when full, by replaying a log of operations and returning each result.
Bounded Recency Store Replay
A bounded key-value store holds at most capacity entries. When a new key would push it past that limit, the entry that was touched longest ago is thrown away.
You are given a log of commands and their arguments, and you must replay them in order and report what each command produces.
Commands
| Command | Arguments | Effect | Output |
|---|---|---|---|
"LRUCache" | [capacity] | Starts a brand-new, empty store with the given capacity. Any earlier store and its contents are discarded. | None |
"put" | [key, value] | Saves value under key. If key is already present, its value is overwritten. Either way, key becomes the most recently touched entry. If a new key was added and the store now holds more than capacity entries, the least recently touched entry is removed. | None |
"get" | [key] | If key is present, returns its value and marks key as the most recently touched. If absent, returns -1 and changes nothing. | the value, or -1 |
Rules
- An entry is "touched" by a
puton its key (new or overwrite) or by a successfulget. Agetthat misses touches nothing. - Overwriting an existing key never changes the number of entries, so it never removes anything.
- A key of
0and a value of0are ordinary valid data. - The first command in every log is
"LRUCache".
Task
Implement replay_recency_store(commands, arguments). Both lists have the same length, and arguments[i] holds the arguments for commands[i]. Return a list of the same length where position i is the output of command i (None where the table says None).
Constraints
1 <= capacity <= 30000 <= key <= 10^40 <= value <= 10^5- The log contains at most
2 * 10^5commands. - Aim for O(1) average time per
getandput.
Examples
Example 1
Input: replay_recency_store(['LRUCache', 'put', 'put', 'get', 'put', 'get', 'put', 'get', 'get', 'get'], [[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]])
Output: [None, None, None, 1, None, -1, None, -1, 3, 4]
Example 2
Input: replay_recency_store(['LRUCache', 'put', 'put', 'get', 'get', 'put', 'get', 'put', 'get', 'get'], [[1], [1, 10], [1, 20], [1], [2], [2, 30], [1], [3, 40], [2], [3]])
Output: [None, None, None, 20, -1, None, -1, None, -1, 40]
Hints
Hint 1
Looking up a key is easy with a hash map. The harder part is knowing which entry was touched longest ago, and updating that ordering cheaply every time something is touched.
Hint 2
Keep the entries in an order from least to most recently touched. Touching a key means pulling it out of its current spot and placing it at the 'most recent' end, in constant time. A doubly linked list plus a hash map from key to node does this, and so does an ordered dictionary.
Hint 3
Evict only after adding a brand-new key and only if the size exceeds capacity. Remember that a missed `get` must not change the order, and that a new `LRUCache` command resets everything.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
We need three things in constant time: find a key, mark it as most recently touched, and find and remove the entry touched longest ago.
A hash map alone cannot track order. A plain list can track order, but moving an element out of the middle costs O(n). So we combine two structures:
- A doubly linked list ordered by recency, with the most recently touched node at one end and the stalest at the other. Dummy sentinel nodes at both ends remove special cases for empty or single-element lists.
- A hash map from key to its list node, so we can reach any node directly and unlink it in O(1).
In Python, collections.OrderedDict is exactly this combination: a hash map backed by a doubly linked list. move_to_end refreshes a key and popitem(last=False) removes the stalest one, both in O(1).
The replay loop handles each command:
"LRUCache": record the capacity, start a fresh empty store, outputNone."get": if the key is missing, output-1without changing anything. Otherwise move it to the most recent end and output its value."put": set the value (new or overwrite), move the key to the most recent end, and if the store now exceeds capacity, drop the stalest entry. OutputNone.
Why it is correct
The invariant is that the order inside the store always equals the order of last touches. Every put and every successful get moves the touched key to the recent end, and nothing else reorders entries, so the entry at the stale end is always the one touched longest ago, which is exactly the one to evict.
Eviction is checked only after a put. Overwriting an existing key leaves the size unchanged, so it can never trigger eviction. Adding a new key grows the size by one, so at most one entry needs to be removed. A missed get leaves the order untouched, as required. Membership is tested with in, never by truthiness, so key 0 and value 0 work properly. Creating a new OrderedDict on "LRUCache" discards all earlier state.
Complexity
- Time: O(1) average per command, so O(m) for m commands.
- Space: O(capacity) for the store plus O(m) for the output list.
Reference solution
from collections import OrderedDict
from typing import List, Optional
def replay_recency_store(commands: List[str], arguments: List[List[int]]) -> List[Optional[int]]:
capacity = 0
store = OrderedDict()
output: List[Optional[int]] = []
for command, args in zip(commands, arguments):
if command == "LRUCache":
capacity = args[0]
store = OrderedDict()
output.append(None)
elif command == "get":
key = args[0]
if key in store:
store.move_to_end(key)
output.append(store[key])
else:
output.append(-1)
elif command == "put":
key, value = args[0], args[1]
store[key] = value
store.move_to_end(key)
if len(store) > capacity:
store.popitem(last=False)
output.append(None)
else:
output.append(None)
return output