Simulate Least-Recently-Used Cache Operations
Data Structure DesignAuto-graded · 19 test casesLast updated
Tests your ability to implement a data structure that maintains access order and performs lookups, updates, and evictions efficiently.
You are given a sequence of cache operations to replay against a fixed-size cache that evicts entries using a least-recently-used (LRU) policy.
Write a function that accepts:
capacity: the maximum number of key-value pairs the cache can hold (may be zero or negative)operations: a list of operation names, each either"get"or"put"arguments: a list of argument lists;arguments[i]corresponds tooperations[i]- For
"get", the argument list contains one integer[key] - For
"put", the argument list contains two integers[key, value]
- For
Return a list of results, one per operation:
"get"returns the stored value if the key exists in the cache, otherwise-1"put"returnsNone
Cache behavior:
- Both
"get"(when the key is found) and"put"mark the key as most recently used - When inserting a new key into a full cache, remove the least recently used entry first
- Updating an existing key (a
"put"where the key is already present) does not trigger eviction - A cache with capacity ≤ 0 can hold nothing; all
"get"operations return-1and all"put"operations are ignored - If an operation name is not
"get"or"put", raise aValueError
Constraints
capacitymay be zero, negative, or positive1 ≤ len(operations) ≤ 10⁵len(operations) == len(arguments)1 ≤ key, value ≤ 10⁶- Each operation is
"get"or"put"(the function should raiseValueErrorfor any other string)
Examples
Example 1
Input: simulate_lru_cache(2, ['put', 'put', 'get', 'put', 'get', 'get', 'get'], [[1, 1], [2, 2], [1], [3, 3], [2], [3], [1]])
Output: [None, None, 1, None, -1, 3, 1]
Example 2
Input: simulate_lru_cache(1, ['put', 'put', 'get', 'put', 'get'], [[1, 10], [1, 20], [1], [2, 30], [1]])
Output: [None, None, 20, None, -1]
Example 3
Input: simulate_lru_cache(0, ['put', 'get', 'put', 'get'], [[1, 10], [1], [2, 20], [2]])
Output: [None, -1, None, -1]
Hints
Hint 1
A hash map gives O(1) lookup by key, but how do you track which entry was used least recently?
Hint 2
A doubly linked list allows O(1) removal from the middle and O(1) append to the end; combine it with a hash map from keys to nodes.
Hint 3
Python's OrderedDict is a hash map with an embedded doubly linked list; move_to_end and popitem(last=False) do exactly what you need.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The challenge is to support three operations in O(1) average time: lookup by key, move an entry to the most-recent position, and evict the least-recent entry.
A hash map alone gives fast lookup but no notion of recency order. An array or plain list makes reordering O(n). A heap gives O(log n) operations and doesn't naturally support "touch this entry."
The classic solution pairs a hash map with a doubly linked list:
- The hash map stores key → node mappings for O(1) lookup
- The doubly linked list maintains entries in access order (least recent at the front, most recent at the back)
- Removing a node from the middle and appending to the tail are both O(1) with proper links
Python's OrderedDict implements exactly this structure. It provides:
move_to_end(key): relinks an entry to the most-recent end in O(1)popitem(last=False): removes the least-recent entry in O(1)
Recency rules:
- A successful
"get"(key exists) moves the key to the most-recent position - A
"put"always marks the key as most recently used, whether inserting new or updating existing - A missing key on
"get"does not affect recency
Edge cases:
- capacity ≤ 0: the cache holds nothing. All
"put"operations are ignored, all"get"operations return-1 - Updating an existing key when at capacity: the size doesn't change, so no eviction occurs. Forgetting to check
if key in cachebefore evicting is a common mistake - capacity = 1: each new insertion evicts the previous entry, unless updating the same key
Why It Works
We maintain the invariant that the ordered dictionary's key sequence matches the order of last access, from oldest to newest. Every "get" hit and every "put" moves or places the key at the back. When we reach capacity and must evict, the front entry is by definition the least recently used.
Complexity
Time: O(m) where m is the number of operations. Each "get" and "put" performs O(1) hash map and linked-list operations on average.
Space: O(capacity) for the cache plus O(m) for the results list.
Solution
from collections import OrderedDict
from typing import List, Optional
def simulate_lru_cache(capacity: int, operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]:
cache = OrderedDict()
results = []
for operation, args in zip(operations, arguments):
if operation == "get":
key = args[0]
if key not in cache:
results.append(-1)
else:
cache.move_to_end(key)
results.append(cache[key])
elif operation == "put":
key, value = args
if capacity <= 0:
results.append(None)
continue
if key in cache:
cache[key] = value
cache.move_to_end(key)
else:
if len(cache) == capacity:
cache.popitem(last=False)
cache[key] = value
results.append(None)
else:
raise ValueError("Unknown operation")
return results