Simulate a Constant-Time LRU Eviction Cache
Data Structure DesignAuto-graded · 19 test casesLast updated
Process a series of lookup and insert requests on a fixed-size Least Recently Used (LRU) key-value cache in O(1) time per operation.
Design an in-memory Least Recently Used (LRU) eviction policy cache that maintains fixed capacity and performs both lookups and insertions in expected constant time.
You are given an initial integer capacity, along with two parallel lists: operations containing the sequence of function calls to execute ("get" or "put"), and arguments containing the inputs for each respective operation.
The cache behaves according to the following specifications:
get(key): Retrieves the integer value associated withkeyif present, returning-1if the key does not exist. Accessing a key marks it as the most recently used entry.put(key, value): Inserts a new key-value pair or updates the existing value ofkey. Both creating a key and updating an existing key mark the item as the most recently used entry. If inserting a new key causes total entries to exceedcapacity, evict the least recently used key prior to completing the request.
Your task is to process all operations in sequential order and return a list of outputs corresponding to each command. For "get", append the returned value (or -1). For "put", append None (represented as null in JSON).
Constraints
1 <= capacity <= 30000 <= key <= 10^40 <= value <= 10^5operationsandargumentshave equal length $N$, with $1 \le N \le 2 \times 10^5$.operations[i]is either"get"or"put".arguments[i]is[key]whenoperations[i]is"get", and[key, value]whenoperations[i]is"put".
Examples
Example 1
Input: lru_cache_operations(2, ['put', 'put', 'get', 'put', 'get', 'put', 'get', 'get', 'get'], [[1, 10], [2, 20], [1], [3, 30], [2], [4, 40], [1], [3], [4]])
Output: [None, None, 10, None, -1, None, -1, 30, 40]
Example 2
Input: lru_cache_operations(2, ['put', 'put', 'get', 'put', 'get', 'get'], [[1, 1], [1, 2], [1], [2, 3], [1], [2]])
Output: [None, None, 2, None, 2, 3]
Hints
Hint 1
To achieve O(1) time complexity for both lookup and eviction reordering, combine a hash map with a doubly linked list.
Hint 2
A hash map provides fast lookup from key to node pointer, while the doubly linked list maintains the precise recency order of items.
Hint 3
Updating an existing key using put() changes its value and moves it to the front of recency order, but does not increase total entry count or cause eviction.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
An LRU Cache must satisfy two main performance constraints concurrently:
- Key Lookup in $O(1)$ time: Requires a hash map mapping keys to entries.
- Order Maintenance & Eviction in $O(1)$ time: Requires moving an item to the "most recent" position or removing the "least recent" item in constant time. A doubly linked list supports node insertion, removal, and relocation in $O(1)$ when a direct pointer/reference to the node is available.
Combining a hash map (key $\to$ node) with a doubly linked list guarantees that:
get(key): If the key is not in the hash map, return-1. Otherwise, retrieve the node, detach it from its current position in the linked list, reattach it at the head (most recently used side), and return its value.put(key, value): If the key is already in the map, update its value, remove it from its list position, and place it at the head. If the key is new, construct a node, insert it at the head, and add it to the map. If the number of items exceedscapacity, detach the node directly preceding the tail (least recently used side) and delete its entry from the map.
In Python, collections.OrderedDict internally maintains a hash table paired with a doubly linked list, enabling straightforward $O(1)$ recency reordering using pop, assignment, and popitem(last=False).
Complexity Analysis
- Time Complexity: $O(1)$ average per
getorputoperation. Executing $N$ operations takes $O(N)$ overall time. - Space Complexity: $O(\text{capacity})$ auxiliary memory for stored key-value nodes, plus $O(N)$ space to build the result list.
Python Source Code
from collections import OrderedDict
from typing import List, Optional
def lru_cache_operations(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:
# Re-insert to mark as most recently used
value = cache.pop(key)
cache[key] = value
results.append(value)
else:
key, value = args
if key in cache:
del cache[key]
cache[key] = value
if len(cache) > capacity:
# Evict the oldest (least recently used) key
cache.popitem(last=False)
results.append(None)
return results