Replay a Bounded Recency Store from an Operation Log
Data Structure DesignAuto-graded · 18 test casesLast updated
Simulate a fixed-size store that discards its stalest entry on overflow, answering lookups in O(1) each by pairing a hash map with a doubly linked list.
Bounded Recency Store Replay
A store holds at most capacity integer key-value pairs. When it is full and a brand-new key arrives, it throws away the entry that was used least recently.
You are given a log of operations to run, in order, on an initially empty store. Return what each operation produces.
Operations
"get"with arguments[key]: ifkeyis in the store, return its value and mark that key as the most recently used. Otherwise return-1and leave the store unchanged."put"with arguments[key, value]:- If
keyis already present, replace its value and mark it as the most recently used. Nothing is evicted. - If
keyis absent, insert it as the most recently used entry. If the store then holds more thancapacityentries, remove the single least recently used entry. - A
putalways producesNone.
- If
"Used" means any successful get or any put on that key.
Input
capacity: the maximum number of entries the store can hold.operations: a list of strings, each either"get"or"put".arguments: a list of the same length asoperations. The entry at indexiholds the arguments foroperations[i]:[key]for aget,[key, value]for aput.
Output
A list with one element per operation, in the same order: the returned value (or -1) for each get, and None for each put.
Aim for O(1) average time per operation, so the whole replay is linear in the number of operations.
Constraints
capacityis a positive integer (at least 1).- Keys and values are integers.
len(operations) == len(arguments).- Re-putting an existing key counts as a use and makes it the most recent.
- A
geton a missing key does not change the store or the recency order.
Examples
Example 1
Input: replay_recency_store(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: replay_recency_store(1, ['put', 'put', 'get', 'put', 'get'], [[1, 10], [1, 20], [1], [2, 30], [1]])
Output: [None, None, 20, None, -1]
Example 3
Input: replay_recency_store(2, ['get', 'put', 'get', 'put', 'put', 'get'], [[5], [1, 100], [1], [2, 200], [3, 300], [1]])
Output: [-1, None, 100, None, None, -1]
Hints
Hint 1
You need two fast capabilities: finding an entry by key, and finding or reordering the least recently used entry. A dictionary gives the first; think about what gives the second.
Hint 2
Keep entries in a doubly linked list ordered by recency, with sentinel nodes at both ends so unlinking and appending never need special cases. Let the dictionary map each key to its node.
Hint 3
Store the key inside each node so that when you evict the oldest node you can also delete it from the dictionary. Only evict when a new key is inserted, never when updating an existing key.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Two operations must be constant time: locating a key, and finding and updating the recency order.
- A dictionary maps each key to its node, so lookup is O(1).
- A doubly linked list keeps the nodes ordered from least to most recently used. Given a node reference, it can be unlinked and re-appended in O(1).
Two sentinel nodes, head and tail, bracket the list. The node right after head is the least recently used, and the node right before tail is the most recently used. Sentinels mean every real node always has both neighbors, so there are no special cases for an empty or single-element list.
Two helpers do the pointer work: unlink(node) and append_recent(node).
Operations:
- get: on a miss, append
-1. On a hit, move the node to the recent end and append its value. - put on an existing key: update the value and move the node to the recent end. The size is unchanged, so nothing is evicted.
- put on a new key: create a node, register it in the dictionary, and append it at the recent end. If the size now exceeds
capacity, unlinkhead.nextand delete its key from the dictionary. This is why each node stores its own key. Aputalways appendsNone.
Why it is correct
After every operation the list holds exactly the keys in the dictionary, ordered from least to most recently used, with at most capacity entries.
- Every use (a
gethit or anyput) moves the node to the recent end, sohead.nextis always the entry untouched for the longest time. - Eviction happens only when a new key pushes the size to
capacity + 1, and it removes exactly one node, restoring the bound. - Since
capacity >= 1, when eviction triggers there are at least two nodes, and the newly added node sits at the recent end, so the evicted node is never the one just inserted. - A
getmiss changes nothing, so it cannot disturb recency.
Complexity
- Time: O(1) average per operation, O(n) for n operations.
- Space: O(capacity) for the structure, plus O(n) for the output.
Reference solution
from typing import List, Optional
def replay_recency_store(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 = None
self.next = None
index = {}
head = Node()
tail = Node()
head.next = tail
tail.prev = head
def unlink(node):
node.prev.next = node.next
node.next.prev = node.prev
def append_recent(node):
node.prev = tail.prev
node.next = tail
tail.prev.next = node
tail.prev = node
result = []
for op, args in zip(operations, arguments):
if op == "get":
key = args[0]
node = index.get(key)
if node is None:
result.append(-1)
else:
unlink(node)
append_recent(node)
result.append(node.value)
elif op == "put":
key, value = args
node = index.get(key)
if node is not None:
node.value = value
unlink(node)
append_recent(node)
else:
node = Node(key, value)
index[key] = node
append_recent(node)
if len(index) > capacity:
oldest = head.next
unlink(oldest)
del index[oldest.key]
result.append(None)
return result