Simulate a Bounded LRU Cache with Get/Put Operations
Data Structure DesignAuto-graded · 15 test casesLast updated
Tests the ability to simulate a fixed-capacity LRU cache by processing a sequence of get/put operations and collecting all get results in order.
Bounded LRU Cache Simulation
You are given a cache capacity and a list of operations to perform on an initially empty LRU (Least Recently Used) cache.
Each operation is a dict with one of two forms:
{"op": "put", "key": <int>, "value": <int>}— Insert or update the entry with the given key. If the cache is already at capacity and the key is new, evict the least recently used entry before inserting.{"op": "get", "key": <int>}— Retrieve the value for the given key. If the key exists, return its value and mark it as most recently used. If the key does not exist, return-1.
Implement the function:
def simulate_lru_cache(capacity: int, operations: list) -> list:
Return a list containing the result of every get operation, in the order the get operations appear. put operations do not contribute to the output list.
LRU Rules (be precise)
- Both a successful
getand aput(whether inserting or updating an existing key) count as a "use" and promote that entry to most recently used. - When eviction is needed, the entry that was used least recently (i.e., longest ago) is removed.
- Capacity is always at least 1.
Constraints
1 ≤ capacity ≤ 1 0000 ≤ len(operations) ≤ 2 000- Each operation's
"op"field is exactly"get"or"put". - All keys and values are integers in the range
[-10 000, 10 000]. - The returned list length equals the number of
getoperations inoperations.
Examples
Example 1
Input: simulate_lru_cache(2, [{'op': 'put', 'key': 1, 'value': 10}, {'op': 'put', 'key': 2, 'value': 20}, {'op': 'get', 'key': 1}, {'op': 'put', 'key': 3, 'value': 30}, {'op': 'get', 'key': 2}, {'op': 'get', 'key': 3}])
Output: [10, -1, 30]
Example 2
Input: simulate_lru_cache(1, [{'op': 'put', 'key': 5, 'value': 99}, {'op': 'get', 'key': 5}, {'op': 'put', 'key': 6, 'value': 42}, {'op': 'get', 'key': 5}, {'op': 'get', 'key': 6}])
Output: [99, -1, 42]
Example 3
Input: simulate_lru_cache(3, [{'op': 'get', 'key': 7}, {'op': 'put', 'key': 1, 'value': 1}, {'op': 'put', 'key': 2, 'value': 2}, {'op': 'put', 'key': 3, 'value': 3}, {'op': 'put', 'key': 4, 'value': 4}, {'op': 'get', 'key': 1}, {'op': 'get', 'key': 3}, {'op': 'get', 'key': 4}])
Output: [-1, -1, 3, 4]
Hints
Hint 1
Use an `OrderedDict` from Python's `collections` module — it remembers insertion order, and `move_to_end` lets you promote an entry to MRU in O(1).
Hint 2
For a `put` on an existing key, update the value AND move it to the most-recently-used end; only evict when the key is brand new and the cache is full.
Hint 3
The return list collects only `get` results; iterate through all operations in order and append to results only when the current operation is a `get`.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key insight
An LRU cache needs two things simultaneously:
- O(1) key lookup.
- O(1) tracking of access order so the least-recently-used entry can be identified and evicted instantly.
Python's collections.OrderedDict provides both: it is a hash map that also maintains a doubly-linked list of insertion order. The move_to_end method re-links a node to the back in O(1), and popitem(last=False) removes the front node (the oldest / LRU) in O(1).
Algorithm
- Maintain an
OrderedDictwhere the front is the LRU entry and the back is the MRU entry. get(key): If the key exists, move it to the back (MRU) and return its value. Otherwise return -1.put(key, value):- If the key already exists, update its value and move it to the back (MRU).
- If the key is new and the cache is full, pop from the front (evict LRU), then insert the new key at the back.
- If the key is new and there is room, just insert at the back.
- Collect results only from
getoperations.
Correctness
Every operation that touches a key (successful get or any put) promotes it to MRU. Eviction always removes the front of the ordered dict, which is exactly the entry that was touched least recently. This faithfully implements the LRU policy.
Complexity
- Time: O(n) total, where n = number of operations — each operation is O(1) amortised thanks to
OrderedDict. - Space: O(capacity) for the cache storage.
from collections import OrderedDict
def simulate_lru_cache(capacity: int, operations: list) -> list:
cache = OrderedDict() # key -> value; LRU at front, MRU at end
results = []
for op in operations:
if op["op"] == "get":
key = op["key"]
if key in cache:
cache.move_to_end(key)
results.append(cache[key])
else:
results.append(-1)
else: # "put"
key = op["key"]
value = op["value"]
if key in cache:
cache.move_to_end(key)
cache[key] = value
else:
if len(cache) >= capacity:
cache.popitem(last=False) # evict LRU
cache[key] = value
return results