Least Recently Used Storage Simulation
Data Structure DesignAuto-graded · 19 test casesLast updated
Simulate a fixed-capacity Least Recently Used (LRU) storage engine that processes lookup and insert operations in O(1) time.
Design and simulate a Least Recently Used (LRU) storage engine with a fixed capacity.
The system processes a sequence of queries operating on key-value pairs:
"get": Accepts a key and retrieves its associated value. If the key exists in storage, its access order is updated so it becomes the most recently used item. If the key does not exist, return-1."put": Accepts a key and a value.- If the key already exists, update its value and mark it as the most recently used item.
- If the key does not exist and the cache capacity is greater than zero:
- If the cache has reached maximum capacity, evict the least recently used key before inserting the new key-value pair.
- Insert the new key-value pair and mark it as the most recently used item.
- If the capacity is
0, no items can ever be stored, so new keys are ignored. - A
"put"operation always returnsNone(represented asnullin JSON output).
Write a function simulate_lru_cache that accepts capacity, a list of string operations, and a list of integer parameter lists arguments. Return a list containing the output of each operation in order.
Constraints
0 <= capacity <= 10000 <= operations.length <= 10**5arguments.length == operations.length- Each operation is either
"get"(witharguments[i]containing[key]) or"put"(witharguments[i]containing[key, value]). - Keys and values are integers in the range
[0, 10**9].
Examples
Example 1
Input: simulate_lru_cache(2, ['put', 'put', 'get', 'put', 'get', 'put', 'get', 'get', 'get'], [[1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]])
Output: [None, None, 1, None, -1, None, -1, 3, 4]
Example 2
Input: simulate_lru_cache(1, ['put', 'get', 'put', 'get'], [[1, 10], [1], [1, 20], [1]])
Output: [None, 10, None, 20]
Example 3
Input: simulate_lru_cache(0, ['put', 'get'], [[1, 1], [1]])
Output: [None, -1]
Hints
Hint 1
To achieve O(1) time complexity for both operations, combine a hash map for key lookups with a doubly linked list for recency ordering.
Hint 2
In Python, `collections.OrderedDict` encapsulates a hash map with a doubly linked list, supporting `.move_to_end(key)` and `.popitem(last=False)`.
Hint 3
Pay close attention to capacity = 0: no items should be stored, and all get operations should return -1.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Method Explanation
An LRU cache requires two main capabilities:
- $O(1)$ lookup and modification by key.
- $O(1)$ recency updates and eviction of the oldest element.
To satisfy both requirements:
- A Hash Map maps each key to its corresponding data node, enabling $O(1)$ random access.
- A Doubly Linked List maintains the access order of keys. Whenever a key is accessed or modified, its node is moved to the tail (most recently used). The head of the list always represents the least recently used element, allowing $O(1)$ eviction.
In Python, collections.OrderedDict internally maintains both structures, making it optimal for implementing an LRU cache cleanly:
move_to_end(key)repositions an existing key to the end (most recent position).popitem(last=False)removes and returns the first inserted/least recently updated item (least recent position).
Edge Cases
- Capacity of 0: If capacity is
0,"put"operations store nothing. Subsequent"get"operations immediately return-1. - Existing Key Updates: Updating an existing key via
"put"must update its recency order without incrementing the item count or triggering an eviction.
Complexity
- Time Complexity: $O(1)$ per operation (
getandput). Processing $N$ operations takes $O(N)$ total time. - Space Complexity: $O(C)$ auxiliary space, where $C$ is the
capacityof the cache, to store up to $C$ key-value entries.
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:
if key in cache:
cache[key] = value
cache.move_to_end(key)
else:
cache[key] = value
if len(cache) > capacity:
cache.popitem(last=False)
results.append(None)
else:
raise ValueError("unknown operation")
return results