Execute Sequence of LRU Cache Instructions
Data Structure DesignAuto-graded · 19 test casesLast updated
Simulate a Least Recently Used (LRU) cache supporting fast lookups, insertions, updates, and capacity evictions across a series of operations.
Construct a simulator for a Least Recently Used (LRU) key-value cache.
The cache has a fixed max capacity and processes a sequence of instruction commands:
"get": Accepts[key]. Returns the stored value if the key is present in the cache; otherwise, returns-1. Successfully retrieving a key marks it as the most recently used item."put": Accepts[key, value]. Inserts or updates the key-value pair.- If the key already exists, update its value and promote it to most recently used without changing cache size or triggering eviction.
- If the key is new, insert it as the most recently used item. If the total number of keys exceeds
capacity, purge the least recently used key. - If
capacityis0, inserting any key has no effect. - Every
"put"operation yieldsNone(represented asnullin JSON output).
Write a function that takes capacity, a list of operation strings operations, and a corresponding list of argument lists arguments, and returns the output produced by each operation in order.
Constraints
- $0 \le \text{capacity} \le 10^4$
- $0 \le \text{len(operations)} = \text{len(arguments)} \le 10^5$
- Each element in
operationsis either"get"or"put". - Arguments for
"get"are single-element lists[key]. - Arguments for
"put"are two-element lists[key, value]. - Keys and values are integers in the range $[-10^9, 10^9]$.
Examples
Example 1
Input: lru_cache_operations(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: lru_cache_operations(1, ['get', 'put', 'get', 'put', 'put', 'get', 'get'], [[1], [1, 10], [1], [2, 20], [1, 15], [2], [1]])
Output: [-1, None, 10, None, None, -1, 15]
Example 3
Input: lru_cache_operations(0, ['put', 'get', 'put', 'get'], [[1, 1], [1], [2, 2], [2]])
Output: [None, -1, None, -1]
Hints
Hint 1
Combine a hash table for O(1) key lookups with a doubly linked list to track usage ordering.
Hint 2
Dummy head and tail sentinel nodes simplify insertion and removal at the list boundaries.
Hint 3
Remember that both successful 'get' operations and 'put' updates/inserts must move the accessed item to the head of the linked list.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To implement an LRU cache where both get and put execute in $O(1)$ average time complexity:
- Hash Table: Maps each
keydirectly to its node in a doubly linked list. This allows constant time key-to-node lookup. - Doubly Linked List: Maintains recency order.
- The front (right after a dummy
headsentinel node) represents the most recently used item. - The back (right before a dummy
tailsentinel node) represents the least recently used item.
- The front (right after a dummy
Operations
-
get(key):- Look up
keyin the hash table. - If missing, append
-1to the output. - If present, detach the node from its current position in the list, re-insert it right after
head, and append itsvalueto the output.
- Look up
-
put(key, value):- Look up
keyin the hash table. - If present, update node's value and move it right after
head. - If absent and
capacity > 0:- Allocate a new node and place it right after
head. - Map
keyto this new node. - If the number of items exceeds
capacity, locate the node right beforetail, remove it from the list, and delete its entry from the hash map.
- Allocate a new node and place it right after
- Append
Noneto the output list.
- Look up
Complexity
- Time Complexity: $O(1)$ amortized per operation. Pointer adjustments and hash map operations take $O(1)$ time. Overall time is $O(N)$ for $N$ total operations.
- Space Complexity: $O(C)$ auxiliary space for storing up to $C$ items in the hash map and doubly linked list, where $C = \text{capacity}$.
from typing import List, Optional
def lru_cache_operations(capacity: int, operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]:
class Node:
__slots__ = ("key", "value", "prev", "next")
def __init__(self, key: int = 0, value: int = 0):
self.key = key
self.value = value
self.prev: Optional["Node"] = None
self.next: Optional["Node"] = None
cache = {}
head = Node()
tail = Node()
head.next = tail
tail.prev = head
def remove(node: Node) -> None:
node.prev.next = node.next
node.next.prev = node.prev
def add_front(node: Node) -> None:
node.next = head.next
node.prev = head
head.next.prev = node
head.next = node
def move_front(node: Node) -> None:
remove(node)
add_front(node)
result = []
for op, args in zip(operations, arguments):
if op == "get":
key = args[0]
node = cache.get(key)
if node is None:
result.append(-1)
else:
move_front(node)
result.append(node.value)
elif op == "put":
key, value = args
node = cache.get(key)
if node is not None:
node.value = value
move_front(node)
elif capacity > 0:
node = Node(key, value)
cache[key] = node
add_front(node)
if len(cache) > capacity:
lru_node = tail.prev
remove(lru_node)
del cache[lru_node.key]
result.append(None)
return result