Simulate a Bounded Cache That Forgets the Least-Used Entry
Data Structure DesignAuto-graded · 20 test casesLast updated
Tests O(1) design of a fixed-size recency-ordered cache: correct eviction order, recency refresh on reads and writes, and update-without-evict semantics.
You are building a cache with a fixed number of slots. When the cache is full and a new key arrives, the entry that was used least recently is discarded to make room. Both reading and writing count as "use."
Implement this behavior by processing a sequence of operations and returning the results of every read.
Function
def simulate_lru_cache(capacity: int, operations: list[str], arguments: list[list[int]]) -> list[int]:
Parameters
capacity— the maximum number of key-value pairs the cache may hold at one time.operations— a list of strings, each either"get"or"put".arguments— parallel list of argument lists:- A
"get"entry contains one integer:[key]. - A
"put"entry contains two integers:[key, value].
- A
Operation Rules
"get" with [key]
- If
keyexists in the cache, record its value as output and promote it to most-recently-used. - If
keyis absent, record-1and leave the cache exactly as it is.
"put" with [key, value]
- If
keyis already cached, overwrite its value and promote it to most-recently-used. The cache size does not change and nothing is evicted. - If
keyis new and the cache is at capacity, first remove the least-recently-used entry, then insert the new key-value pair as most-recently-used. - If
keyis new and the cache is not yet full, insert the new pair as most-recently-used directly.
Return Value
A list of integers containing the result of every "get" operation, in the order the gets appear in operations.
Constraints
1 <= capacity <= 10^41 <= len(operations) == len(arguments) <= 2 × 10^5- Every string in
operationsis"get"or"put". 0 <= key <= 10^90 <= value <= 10^90is a valid value; absence is always indicated by-1, never by0.
Examples
Example 1
Input: simulate_lru_cache(2, ['put', 'put', 'get', 'put', 'get', 'get', 'put', 'get', 'get'], [[1, 10], [2, 20], [1], [3, 30], [2], [3], [1, 11], [1], [3]])
Output: [10, -1, 30, 11, 30]
Example 2
Input: simulate_lru_cache(2, ['put', 'put', 'put', 'get', 'put', 'get', 'get'], [[4, 1], [5, 2], [4, 3], [5], [6, 4], [4], [5]])
Output: [2, -1, 2]
Example 3
Input: simulate_lru_cache(1, ['get', 'put', 'put', 'get', 'get'], [[5], [5, 7], [6, 8], [5], [6]])
Output: [-1, -1, 8]
Hints
Hint 1
You need O(1) lookup by key and O(1) promotion to most-recently-used. Think about which standard data structure combines a hash map with an ordered sequence that supports constant-time reordering.
Hint 2
Python's collections.OrderedDict keeps keys in insertion order and provides move_to_end(key) and popitem(last=False) — exactly the two recency operations you need.
Hint 3
Be careful to distinguish an update (key already present) from an insert (key is new). An update must refresh recency but must never trigger eviction, even when the cache is full.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
What the problem needs
Every operation has two requirements that must both be O(1):
- Key lookup — find whether a key exists and read its value.
- Recency tracking — move any entry to the "most recent" position, and remove the entry at the "least recent" position.
A hash map satisfies requirement 1. A doubly linked list satisfies requirement 2, because splicing out a node you already hold is O(1). The classic combination is a hash map from key to list node, with the list ordered from least-recently-used to most-recently-used.
Using OrderedDict
Python's collections.OrderedDict is exactly that structure under the hood. It is a dictionary whose keys maintain a doubly linked insertion order, with two extra methods:
move_to_end(key)— re-links the node forkeyto the back of the list (most recent). O(1).popitem(last=False)— removes and returns the front item (least recent). O(1).
Both operations map directly onto the cache rules, so the solution is a thin wrapper around OrderedDict.
Invariant
At every point in the simulation, the order of keys in the OrderedDict matches the order of their most recent use, oldest first. Maintaining this invariant makes the front key always the correct eviction target.
- A new key is appended at the back (most recent) automatically.
- A successful
getcallsmove_to_end, putting that key at the back. - A
puton an existing key updates the value and callsmove_to_end. The cache size is unchanged, so no eviction check is needed. - A missed
gettouches nothing, preserving the order.
Two subtleties to watch
Updates never evict. If the key is already present, the cache size does not grow. Checking capacity before checking membership would wrongly evict a valid entry when updating a key in a full cache.
Assigning to an existing key does not reorder it. cache[key] = value keeps the key's current position in an OrderedDict. The explicit move_to_end after the assignment is required to refresh recency.
Trace of sample 2 (capacity 2)
| Step | Operation | Cache order (LRU → MRU) | Output |
|---|---|---|---|
| 1 | put(4, 1) | [4] | |
| 2 | put(5, 2) | [4, 5] | |
| 3 | put(4, 3) | [5, 4] | ← update, move 4 to back |
| 4 | get(5) | [4, 5] | 2 |
| 5 | put(6, 4) | evict 4 → [5, 6] | |
| 6 | get(4) | [5, 6] | -1 |
| 7 | get(5) | [6, 5] | 2 |
Result: [2, -1, 2].
Complexity
- Time: O(1) average per operation (hash lookup + linked-list splice), so O(n) overall for n operations.
- Space: O(capacity) for the cache, plus O(g) for the output list where g is the number of
getoperations.
Reference solution
from collections import OrderedDict
from typing import List
def simulate_lru_cache(capacity: int, operations: List[str], arguments: List[List[int]]) -> List[int]:
# front of the OrderedDict = least recently used
# back of the OrderedDict = most recently used
cache: OrderedDict = OrderedDict()
results: List[int] = []
for op, args in zip(operations, arguments):
if op == "get":
key = args[0]
if key in cache:
cache.move_to_end(key) # promote to most-recently-used
results.append(cache[key])
else:
results.append(-1) # miss: cache unchanged
else: # "put"
key, value = args[0], args[1]
if key in cache:
cache[key] = value # update value in place
cache.move_to_end(key) # refresh recency; no eviction
else:
if len(cache) >= capacity:
cache.popitem(last=False) # evict the least-recently-used entry
cache[key] = value # new key appended as most-recently-used
return results
Building it without OrderedDict
If the interviewer asks for a ground-up implementation, use a hash map from key to node plus a doubly linked list with sentinel head and tail nodes. Sentinels eliminate every boundary check for an empty list or single-element list.
class _Node:
__slots__ = ("key", "val", "prev", "next")
def __init__(self, key=0, val=0):
self.key = key
self.val = val
self.prev = self.next = None
class _LRUCache:
def __init__(self, capacity: int):
self.cap = capacity
self.map = {}
# sentinel nodes: head.next = LRU end, tail.prev = MRU end
self.head, self.tail = _Node(), _Node()
self.head.next, self.tail.prev = self.tail, self.head
def _unlink(self, node):
node.prev.next, node.next.prev = node.next, node.prev
def _append_mru(self, node):
node.prev, node.next = self.tail.prev, self.tail
self.tail.prev.next = node
self.tail.prev = node
def get(self, key: int) -> int:
node = self.map.get(key)
if node is None:
return -1
self._unlink(node)
self._append_mru(node)
return node.val
def put(self, key: int, value: int) -> None:
node = self.map.get(key)
if node is not None:
node.val = value
self._unlink(node)
self._append_mru(node)
return
if len(self.map) >= self.cap:
lru = self.head.next # least-recently-used sits right of head sentinel
self._unlink(lru)
del self.map[lru.key] # node stores its own key so the map entry can be removed
node = _Node(key, value)
self.map[key] = node
self._append_mru(node)
Two details worth calling out: each node stores its own key so that on eviction the map entry can be found and deleted; and the list must be doubly linked because unlinking an arbitrary node in O(1) requires a prev pointer.