Recency-Evicting Cache Simulator
Data Structure DesignAuto-graded · 14 test casesLast updated
Simulate a fixed-capacity key-value store that evicts the least recently used entry, processing a batch of get and put commands in constant time each.
Recency-Evicting Cache Simulator
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 away the entry that was used least recently.
Return the result of every command.
Commands
Command i is commands[i], and its arguments are params[i].
"get"withparams[i] = [key]: ifkeyis in the store, the result is its value. Otherwise the result is-1. A successful lookup makes that key the most recently used one. A failed lookup changes nothing."put"withparams[i] = [key, value]: the result isNone.- If
keyis already stored, replace its value and mark it as the most recently used. No entry is evicted, since the number of entries does not change. - If
keyis new, insert it as the most recently used entry. If the store then holds more thancapacityentries, remove the least recently used one.
- If
The store starts empty. Only successful get calls and put calls (both inserts and updates) count as "using" a key.
Output
Return a list with one element per command, in the same order: the retrieved value or -1 for each get, and None for each put.
Performance goal
Each command should take O(1) time on average, so the whole batch runs in time linear in the number of commands.
Constraints
capacityis a positive integer.commandsandparamshave the same length, at most10^5.- Each command is either
"get"or"put", with the argument list matching its form above. - Keys and values are integers.
- Capacity 1 is valid, and
geton a missing key is valid.
Examples
Example 1
Input: simulate_recency_cache(2, ['put', 'put', 'get', 'put', 'get'], [[1, 1], [2, 2], [1], [3, 3], [2]])
Output: [None, None, 1, None, -1]
Example 2
Input: simulate_recency_cache(2, ['put', 'put', 'get', 'put', 'get', 'get', 'put', 'get'], [[1, 10], [2, 20], [1], [1, 15], [2], [1], [3, 30], [3]])
Output: [None, None, 10, None, 20, 15, None, 30]
Hints
Hint 1
Two things are needed at once: finding a key instantly, and knowing which key was touched longest ago. Think about which structure gives each.
Hint 2
A hash map alone cannot cheaply move an entry to the 'newest' position. A doubly linked list lets you unlink a node you already hold in O(1), so have the map point directly at list nodes.
Hint 3
Check whether the key already exists before deciding to evict. Updating an existing key in a full store must never remove anything. Also store the key inside each node so you can delete the map entry when you evict.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The store needs two abilities at once:
- Look up a key in O(1). A hash map does this.
- Move any entry to the "newest" position and drop the "oldest" entry, both in O(1). A doubly linked list does this, because a node you already hold can be unlinked by rewiring its two neighbours.
Combine them. The map sends each key to its list node, and the list is ordered by recency, with the newest entries at one end and the oldest at the other. Each node also stores its key, so that when the oldest node is evicted you can delete the matching map entry.
Python's OrderedDict is exactly this combination. It is a hash map that also remembers insertion order, and move_to_end and popitem(last=False) are O(1). The reference solution keeps the oldest entry at the front and the newest at the back.
Processing each command:
- get: if the key is missing, record
-1and change nothing. Otherwise move the key to the newest end and record its value. - put: if the key exists, move it to the newest end and overwrite the value. If it is new, insert it at the newest end. Then, if the size exceeds
capacity, remove the oldest entry. This can only happen after inserting a new key, because updating keeps the size the same. RecordNone.
Why it is correct
- Consistency: every stored key appears exactly once in the ordered structure, and removal and insertion always happen together.
- Recency order: every successful
getand everyputmoves the touched key to the newest end, and untouched keys keep their relative order. The front of the structure is therefore always the entry that was used longest ago. - Capacity: eviction runs right after any insert that pushes the size past
capacity, so the size never stays above the limit, and the evicted entry is always the true least recently used one. - Edge cases: a missing
getleaves the order untouched. With capacity 1, every new key evicts the single existing one. Updating an existing key in a full store moves it to the newest end without evicting anything.
Complexity
- Time: O(1) average per command, so O(n) for n commands.
- Space: O(capacity) for the stored entries, plus O(n) for the result list.
Reference solution
from typing import List, Optional
from collections import OrderedDict
def simulate_recency_cache(capacity: int, commands: List[str], params: List[List[int]]) -> List[Optional[int]]:
store = OrderedDict() # least recently used first, most recently used last
results = []
for cmd, p in zip(commands, params):
if cmd == "get":
key = p[0]
if key not in store:
results.append(-1)
else:
store.move_to_end(key)
results.append(store[key])
elif cmd == "put":
key, value = p
if key in store:
store.move_to_end(key)
store[key] = value
if len(store) > capacity:
store.popitem(last=False)
results.append(None)
return results