Simulate a Least Recently Used Cache with Fixed Capacity
Data Structure DesignAuto-graded · 21 test casesLast updated
Tests understanding of LRU eviction policy through hash map and doubly-linked list composition to achieve O(1) operations.
You are given a sequence of cache operations to simulate on a least recently used (LRU) cache with a fixed maximum capacity.
An LRU cache maintains key-value pairs and discards the least recently accessed entry when inserting a new key would exceed capacity. Both retrieval and insertion count as an access that updates recency.
Your task is to process a list of operations and return their results.
Operations
You will receive three parallel inputs:
operations: a list of operation names, each either"get"or"put"arguments: a list of argument lists corresponding to each operationcapacity: the maximum number of key-value pairs the cache can hold
Each operation behaves as follows:
getwith argument[key]: ifkeyexists in the cache, mark it as recently used and return its value; otherwise returnNone. This counts as an access.putwith arguments[key, value]: insert or update the key-value pair and mark it as recently used. If this insertion would exceed capacity andkeyis new, first remove the least recently used key. If capacity is zero, ignore all put operations. This counts as an access.
Return a list where each element corresponds to one operation: the returned value for get operations, or None for put operations.
Constraints
1 ≤ len(operations) ≤ 10^4operations[i]is either"get"or"put"0 ≤ capacity ≤ 10^4- All keys and values are integers
len(operations) == len(arguments)- Each
arguments[i]has length 1 for"get"and length 2 for"put"
Examples
Example 1
Input: simulate_lru_cache(['put', 'put', 'get', 'put', 'get', 'get'], [[1, 10], [2, 20], [1], [3, 30], [2], [1]], 2)
Output: [None, None, 10, None, None, 10]
Example 2
Input: simulate_lru_cache(['put', 'put', 'get', 'put', 'get', 'get', 'get'], [[1, 1], [2, 2], [1], [3, 3], [2], [3], [1]], 2)
Output: [None, None, 1, None, None, 3, 1]
Example 3
Input: simulate_lru_cache(['get', 'put', 'get', 'put', 'get'], [[5], [1, 100], [5], [2, 200], [1]], 0)
Output: [None, None, None, None, None]
Hints
Hint 1
A hash map provides O(1) lookup, but how do you track which entry is least recently used?
Hint 2
A doubly-linked list can maintain access order efficiently if you can find and move nodes in O(1) time.
Hint 3
Store both the value and a reference to the list node in your hash map so you can reorder the list when a key is accessed.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
An LRU cache requires constant-time lookup, insertion, and eviction of the least recently used item. This demands a combination of two data structures:
- Hash map: provides O(1) key lookup
- Doubly-linked list: maintains access order where the most recent item is at one end and the least recent at the other
Python's OrderedDict elegantly combines both: it maintains insertion order and allows us to move items to the end (marking them as recently used) by removing and reinserting them. When the cache exceeds capacity, we evict the first item using popitem(last=False).
Algorithm
For each operation:
- get(key): If the key exists, remove it and reinsert it (moving it to the end), then return its value. Otherwise return
None. - put(key, value): If capacity is zero, ignore the operation. Otherwise, if the key exists, remove it first. Insert the key-value pair at the end. If this causes the size to exceed capacity, remove the first (least recently used) item.
Both operations maintain the invariant that the most recently accessed item is at the end of the ordered dictionary.
Why This Works
- Each
getorputon an existing key moves it to the end by removing and reinserting it - Each new insertion goes to the end
- The front always holds the least recently used item, making eviction trivial
- All operations (lookup, remove, insert at end, remove from front) run in O(1) average time
Complexity
- Time: O(n) where n is the number of operations, with each operation taking O(1) average time
- Space: O(min(capacity, number of unique keys inserted))
Solution
from collections import OrderedDict
from typing import List, Optional
def simulate_lru_cache(operations: List[str], arguments: List[List[int]], capacity: 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(None)
else:
value = cache.pop(key)
cache[key] = value
results.append(value)
else: # put
key, value = args
if capacity > 0:
if key in cache:
cache.pop(key)
cache[key] = value
if len(cache) > capacity:
cache.popitem(last=False)
results.append(None)
return results