Replay a Sequence of Recency-Evicting Cache Commands
Data Structure DesignAuto-graded · 18 test casesLast updated
Simulate a fixed-capacity cache that evicts the least recently used entry, replaying a list of get/put commands and returning each command's result.
Replay a Recency-Evicting Cache
You are given the size limit of a small key-value store and a list of commands to run against it, in order. The store keeps at most capacity entries. When it is full and a brand-new key arrives, it throws out the entry that was used least recently.
Implement a function that runs all the commands on an initially empty store and reports the outcome of each one.
Commands
Each command is named in commands, and the entry at the same index in params holds its integer parameters.
"get"withparams = [key]: Look upkey.- If it is stored, the result is its value, and the key now counts as the most recently used.
- If it is not stored, the result is
-1and nothing changes.
"put"withparams = [key, value]: Savevalueunderkey.- If
keyis already stored, replace its value and mark it as the most recently used. Nothing is evicted. - If
keyis new and the store already holdscapacityentries, first remove the least recently used entry, then insert the new key as the most recently used. - If
keyis new and there is room, simply insert it as the most recently used. - The result of a
putisNone.
- If
An entry's "use" is any successful get or any put on its key.
Output
Return a list with one element per command, in order: the retrieved value (or -1) for each get, and None for each put.
Constraints
1 <= capacity <= 100000commandsandparamshave the same length.- Every command is either
"get"or"put", and itsparamslist has the matching number of integers. - Each command should run in O(1) average time.
- A failed
get(missing key) does not affect recency of any entry.
Examples
Example 1
Input: replay_cache_commands(2, ['put', 'put', 'get', 'put', 'get'], [[1, 1], [2, 2], [1], [3, 3], [2]])
Output: [None, None, 1, None, -1]
Example 2
Input: replay_cache_commands(2, ['put', 'put', 'put', 'get', 'get', 'get'], [[1, 10], [2, 20], [1, 15], [1], [2], [3]])
Output: [None, None, None, 15, 20, -1]
Example 3
Input: replay_cache_commands(1, ['get', 'put', 'get', 'put', 'get'], [[7], [7, 70], [7], [8, 80], [7]])
Output: [-1, None, 70, None, -1]
Hints
Hint 1
You need constant-time lookup by key and constant-time reordering by recency. Think about combining a hash map with an ordering structure that lets you move any item to the 'newest' end cheaply.
Hint 2
Keep entries ordered from least to most recently used. A successful get, or a put on an existing key, moves that key to the newest end; eviction removes from the oldest end.
Hint 3
Only evict when inserting a key that is not already present and the store is already at capacity. Updating an existing key must never trigger an eviction. In Python, collections.OrderedDict gives you move-to-end and pop-oldest in O(1).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
We need two things in constant time: finding an entry by key, and keeping entries ordered by how recently they were used. A hash map combined with a doubly linked list does exactly this. The map points straight at list nodes, so any node can be unlinked and re-attached at the "newest" end in O(1), and the oldest node sits at the other end ready to be evicted.
Python's collections.OrderedDict is this structure already. move_to_end(key) and popitem(last=False) are both O(1).
We keep the oldest entry at the front and the newest at the back, then process commands one by one:
- get: If the key is absent, record
-1. Otherwise move it to the back and record its value. - put:
- Existing key: move it to the back and overwrite the value. No eviction.
- New key with a full store: remove the front entry, then insert at the back.
- New key with room: insert at the back.
- Record
None.
Why It Is Correct
- Order invariant: After every command, the dictionary order equals usage order, oldest to newest, because every successful
getand everyputmoves or inserts its key at the back. The front is therefore always the least recently used key. - Capacity invariant: Eviction happens only when inserting a new key into a full store, so size never exceeds
capacity, and updates never evict anything. - Failed gets do not touch the order, matching the rules.
Complexity
- Time: O(1) average per command, O(m) for m commands.
- Space: O(capacity) for the store, plus O(m) for the result list.
Reference Solution
from collections import OrderedDict
from typing import List, Optional
def replay_cache_commands(capacity: int, commands: List[str], params: List[List[int]]) -> List[Optional[int]]:
store = OrderedDict()
results: List[Optional[int]] = []
for command, args in zip(commands, params):
if command == "get":
key = args[0]
if key not in store:
results.append(-1)
else:
store.move_to_end(key)
results.append(store[key])
elif command == "put":
key, value = args
if key in store:
store.move_to_end(key)
elif len(store) == capacity:
store.popitem(last=False)
store[key] = value
results.append(None)
return results