Build a Fixed-Capacity Recency-Ordered Cache
Data Structure DesignAuto-graded · 17 test casesLast updated
Tests whether you can design a cache that evicts the least-recently-touched entry in O(1) time using a hash map paired with an ordered structure.
Fixed-Capacity Recency-Ordered Cache
You need to build a cache that holds at most capacity key-value pairs and always discards the entry that was touched least recently when space runs out.
Operations
The cache must support two operations.
put(key, value)
- If
keyis already in the cache, overwrite its value and mark it as the most recently used entry. - If
keyis not in the cache, insert the pair. - After inserting a brand-new key, if the number of stored entries now exceeds
capacity, remove whichever entry was used least recently.
get(key)
- If
keyexists, mark it as the most recently used entry and return its value. - If
keydoes not exist, return-1without changing anything.
Both operations must run in O(1) average time.
Simulation Interface
Rather than instantiating a class directly, implement a single function that replays a sequence of operations and collects their return values.
run_recency_cache(capacity, operations, arguments)
capacity— maximum number of entries the cache may hold at any moment (positive integer).operations— a list of strings, each either"put"or"get".arguments— a parallel list; for"put"each element is[key, value], for"get"each element is[key].
Return a list with one entry per operation:
- For
"get": the value found, or-1. - For
"put":None.
Constraints
1 <= capacity <= 30000 <= key <= 10^40 <= value <= 10^51 <= len(operations) <= 3 * 10^4operations[i]is either"get"or"put".arguments[i]has exactly one element for"get"and exactly two for"put".- A
"get"on a missing key must return-1and must not alter the recency order of any existing entry. - A
"put"on an existing key updates the value and refreshes recency but never triggers an eviction, even if the cache was already at capacity.
Examples
Example 1
Input: run_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: run_recency_cache(1, ['put', 'get', 'put', 'get', 'get'], [[1, 10], [1], [2, 20], [1], [2]])
Output: [None, 10, None, -1, 20]
Hints
Hint 1
You need O(1) lookup by key and O(1) reordering by recency at the same time — think about what single Python built-in combines both properties.
Hint 2
Treat the ordered structure as a queue where the front is the least-recently-used end and the back is the most-recently-used end. Every successful access pops and reinserts the touched key so it lands at the back.
Hint 3
When a put arrives for a key that already exists, the cache size does not grow, so no eviction should occur — handle the update path separately before checking the size.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core idea
The problem demands two things simultaneously:
- O(1) lookup — given a key, retrieve or update its value instantly.
- O(1) recency tracking — move any entry to the "most recently used" position and remove the "least recently used" entry instantly.
A plain dictionary handles (1) but cannot do (2) efficiently on its own. A doubly linked list handles (2) but not (1). Python's collections.OrderedDict fuses both: it is a hash map whose entries are connected by a doubly linked list in insertion order. We hijack that order to mean recency order.
The invariant throughout the simulation is:
The entry at the front of the ordered structure is the least recently used; the entry at the back is the most recently used.
Operation walkthrough
get(key)
- If
keyis absent, append-1and do nothing else. - If
keyis present, pop it (O(1) hash removal + list unlink) and reinsert it (O(1) list append at the back). This moves it to the MRU position while leaving every other entry's relative order intact. Append the retrieved value.
put(key, value)
- If
keyalready exists, pop it first. This ensures the subsequent insertion lands at the MRU end rather than keeping the old position. The size stays the same, so no eviction check is needed — or rather, the check will findlen == capacity(not over), which is correct. - Insert
key -> valueat the MRU end. - If
len(cache) > capacity, callpopitem(last=False)to drop the front entry, which is by definition the least recently used one. - Append
None.
Why it is correct
Every path that touches a key moves it to the MRU end. Keys that are not touched keep their relative order. So after every operation the invariant still holds. When eviction fires, popitem(last=False) removes the front element, which the invariant guarantees is the least recently used entry.
Updating an existing key never increases the cache size, so it never triggers eviction. This matches the spec: a put on a key already in a full cache is a pure update.
A failed get leaves the structure completely unchanged, which is also required.
Complexity
- Time: O(1) average per operation.
OrderedDictpop and reinsert are O(1) average. The full simulation over n operations is O(n). - Space: O(capacity) for the cache itself, plus O(n) for the output list.
Edge cases
geton a missing key — returns-1, no state change.putupdating an existing key — refreshes recency, no eviction.putadding a new key to a full cache — evicts exactly the LRU entry.- Capacity of 1 — every new key immediately evicts the previous one; updating the same key does not evict anything.
- A
getbetween twoputcalls can change which entry is evicted next (it rescues the accessed key from the LRU position).
Reference solution
from collections import OrderedDict
from typing import List, Optional
def run_recency_cache(capacity: int, operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]:
cache = OrderedDict() # front = least recently used, back = most recently used
result = []
for operation, args in zip(operations, arguments):
if operation == "get":
key = args[0]
if key not in cache:
result.append(-1)
else:
value = cache.pop(key) # remove from current position...
cache[key] = value # ...and reinsert at the MRU end
result.append(value)
elif operation == "put":
key, value = args
if key in cache:
cache.pop(key) # remove so reinsertion refreshes recency
cache[key] = value # insert at MRU end
if len(cache) > capacity:
cache.popitem(last=False) # drop the LRU entry (front)
result.append(None)
return result
Going deeper: the hand-rolled version
If asked to avoid OrderedDict, build the same structure explicitly: a hash map of key -> node paired with a doubly linked list using sentinel head and tail nodes. Each node must store its own key so that when you unlink it during eviction you can also delete it from the hash map in O(1). The _unlink and _append helpers each touch a constant number of pointers, keeping both operations O(1) worst case rather than O(1) amortized.