Replay Operations on a Bounded LRU Cache
Data Structure DesignAuto-graded · 22 test casesLast updated
Tests understanding of least-recently-used eviction by executing a sequence of cache operations and collecting their return values.
You are given a sequence of operations to execute on a fixed-capacity cache with least-recently-used (LRU) eviction. Your task is to simulate these operations and return their results.
The cache stores string key-value pairs. When the cache reaches capacity and a new key is inserted, the least recently accessed key is evicted.
Input Format:
operations: list of operation namesarguments: parallel list of argument lists
Operations:
"SecureCache"with[capacity]: Initialize or reset the cache to the given capacity. ReturnsNone."put"with[key, value]: Store or update a key-value pair. ReturnsNone."get"with[key]: Retrieve the value for the key. Returns the value string if found, otherwiseNone.
LRU Behavior:
- Both
getandputcount as accessing a key, making it the most recently used. - When
putis called on an existing key, update its value and mark it as most recently used. This does not trigger eviction. - When
putinserts a new key and the cache is at capacity, evict the least recently used key first, then insert the new one. geton a missing key returnsNoneand does not affect cache state.- If capacity is 0 or negative, all
putoperations are ignored (cache remains empty).
Output Format: Return a list containing one result per operation:
"SecureCache"and"put":None"get": the value string orNone
Constraints:
- 1 ≤ number of operations ≤ 1000
- 0 ≤ capacity ≤ 100
- Keys and values are non-empty strings with length ≤ 100
- The first operation is always
"SecureCache"
Examples
Example 1
Input: simulate_lru_cache(['SecureCache', 'put', 'put', 'get', 'put', 'get', 'get'], [[2], ['A', '123 Main'], ['B', '456 Oak'], ['A'], ['C', '789 Pine'], ['B'], ['C']])
Output: [None, None, None, '123 Main', None, None, '789 Pine']
Example 2
Input: simulate_lru_cache(['SecureCache', 'put', 'get', 'put', 'get'], [[1], ['home', '123 Main St'], ['home'], ['home', '456 Oak Ave'], ['home']])
Output: [None, None, '123 Main St', None, '456 Oak Ave']
Hints
Hint 1
OrderedDict tracks insertion order and provides move_to_end to reposition keys efficiently.
Hint 2
When updating an existing key with put, move it to most-recent position before checking capacity.
Hint 3
Eviction only happens when inserting a new key while at capacity—never when updating an existing key.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
We need to simulate a cache that tracks access order and evicts the least recently used entry when full. Python's OrderedDict is ideal: it maintains key insertion order and provides move_to_end(key) to reposition entries in O(1) time.
Key insight: In an OrderedDict, the leftmost entry is oldest (least recent) and the rightmost is newest (most recent). Both reading and writing a key make it most recent.
Algorithm:
For each operation:
- SecureCache: Store the capacity and clear any existing cache
- put:
- If capacity is 0 or less, do nothing
- If the key already exists, move it to the end (most recent position)
- Set or update the key's value
- If we now exceed capacity, remove the leftmost (least recent) entry
- get:
- If the key doesn't exist, return
None - Otherwise, move it to the end and return its value
- If the key doesn't exist, return
Critical details:
- Moving an existing key to the end happens before setting its value. This ensures the key is marked as recently used even if the value changes.
- Eviction only occurs when
len(cache) > capacityafter assignment, which only happens when inserting a brand-new key at capacity. - Updating an existing key never causes eviction because the length doesn't increase.
Why it's correct:
The OrderedDict maintains exact chronological order of accesses. move_to_end simulates "touching" a key. popitem(last=False) removes from the left (oldest). By checking length after assignment, we evict exactly when needed.
Complexity:
- Time: O(1) per operation (OrderedDict guarantees O(1) for all operations used)
- Space: O(capacity) to store up to
capacityentries
from collections import OrderedDict
from typing import List, Optional
def simulate_lru_cache(operations: List[str], arguments: List[List]) -> List[Optional[str]]:
cache = OrderedDict()
capacity = 0
results = []
for operation, args in zip(operations, arguments):
if operation == "SecureCache":
capacity = args[0]
cache.clear()
results.append(None)
elif operation == "put":
key, value = args
if capacity > 0:
if key in cache:
cache.move_to_end(key)
cache[key] = value
if len(cache) > capacity:
cache.popitem(last=False)
results.append(None)
elif operation == "get":
key = args[0]
if key not in cache:
results.append(None)
else:
cache.move_to_end(key)
results.append(cache[key])
else:
raise ValueError("unknown operation")
return results