Run a Command Log on a Recency Cache with Live Mean
Data Structure DesignAuto-graded · 19 test casesLast updated
Simulate a fixed-capacity least-recently-used cache from a command log, answering lookups and the mean of stored values, each in expected constant time.
Run a Command Log on a Recency Cache with Live Mean
You are simulating a small in-memory cache that holds at most capacity entries. Each key is a string and each value is a signed number. The cache evicts the entry that was used least recently whenever it grows too large. It can also report the mean of the values it currently holds.
You are given the cache's capacity and a log of commands. Process the commands in order, starting from an empty cache, and return one result per command.
Commands
operations[i] is the name of the i-th command, and arguments[i] is its list of arguments.
"get"witharguments[i] = [key]- If
keyis in the cache, the result is its value, andkeybecomes the most recently used entry. - If
keyis not in the cache, the result isNone. The cache is not changed.
- If
"put"witharguments[i] = [key, value]- If
keyis already present, its value is replaced. Otherwise a new entry is added. - In both cases
keybecomes the most recently used entry. - If the cache now holds more than
capacityentries, the least recently used entry is removed. Only a newly added key can push the cache over capacity, so replacing an existing key never causes an eviction. - The result is always
None.
- If
"get_average"witharguments[i] = []- The result is the arithmetic mean (sum divided by count) of the values of the entries currently in the cache. Entries that were evicted or overwritten earlier do not count.
- If the cache is empty, the result is
None. - The cache is not changed, and recency is not affected.
Return a list of results, one for each command, in the same order as the log.
Requirements
Every command should run in expected O(1) time, so the whole log is processed in O(n) for n commands. Scanning the entries, or relying on a list whose removal from the middle is linear, will be too slow on large inputs.
Constraints
1 <= capacity, and the capacity is fixed for the whole log.len(operations) == len(arguments).- Every command name is one of
"get","put","get_average". - Keys are strings, and values are integers (positive, zero, or negative).
- A missed
getdoes not alter recency or the average. - Updating an existing key replaces its value and refreshes its recency.
- Averages are computed over the current contents only, as
sum / count.
Examples
Example 1
Input: simulate_cache_log(2, ['put', 'put', 'get', 'put', 'get', 'get_average'], [['a', 1], ['b', 2], ['a'], ['c', 3], ['b'], []])
Output: [None, None, 1, None, None, 2]
Example 2
Input: simulate_cache_log(1, ['get_average', 'put', 'get_average', 'put', 'get', 'get_average'], [[], ['x', -4], [], ['x', 6], ['x'], []])
Output: [None, None, -4, None, 6, 6]
Example 3
Input: simulate_cache_log(3, ['put', 'put', 'get_average', 'get', 'get_average'], [['a', 2], ['b', 4], [], ['a'], []])
Output: [None, None, 3, 2, 3]
Hints
Hint 1
Pair a hash map from key to node with a doubly linked list ordered by recency, so you can unlink a node and move it to the 'newest' end without scanning.
Hint 2
Keep a running total of all stored values. Subtract the old value on replacement, add the new value on insertion, and subtract the removed value on eviction. The mean is then total divided by the entry count.
Hint 3
Sentinel head and tail nodes remove most special cases when linking and unlinking. Remember that replacing an existing key must not evict anything, and a missed get or an average query must not touch the order.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Combine three pieces of state:
- A hash map from key to a node, giving expected
O(1)lookup. - A doubly linked list of nodes ordered by recency. The node after the head sentinel is the least recently used, and the node before the tail sentinel is the most recently used. Because each node knows its neighbours, it can be unlinked and re-appended at the newest end in
O(1). - A running
totalof all values currently stored.
Command handling:
- get: look up the node. On a miss, return
Noneand change nothing. On a hit, move the node to the newest end and return its value. - put: if the key exists, add
new - oldto the total, overwrite the value, and move the node to the newest end. No eviction can happen, since the entry count is unchanged. If the key is new, create a node, append it, and add its value to the total. If the count now exceedscapacity, unlink the node after the head (the least recently used), delete it from the map, and subtract its value from the total. - get_average: return
total / len(index), orNoneif the cache is empty. This does not alter any state.
Why it is correct
The invariant is that the map and the list contain exactly the same entries, the list order is increasing recency, and total equals the sum of the values of those entries. Each operation preserves it:
- Replacement adjusts the total by the difference.
- Insertion adds the new value.
- Eviction subtracts the removed value.
- Misses and average queries modify nothing.
Because total always matches the current contents, the mean ignores evicted or overwritten values. Because every hit or write moves its node to the newest end, the node next to the head is always the true least recently used entry.
Complexity
- Time: expected
O(1)per command, soO(n)for a log ofncommands. - Space:
O(capacity)for the map and list, plusO(n)for the output.
With integer values, Python's arbitrary-precision integers keep the running total exact, so there is no overflow or drift. Only the final division produces a float.
Reference solution
from typing import List, Optional
class _Node:
__slots__ = ("key", "value", "prev", "next")
def __init__(self, key, value):
self.key = key
self.value = value
self.prev = None
self.next = None
def simulate_cache_log(capacity: int, operations: List[str], arguments: List[List]) -> List[Optional[float]]:
index = {}
# Sentinels: head.next is the least recently used, tail.prev is the most recent.
head = _Node(None, 0)
tail = _Node(None, 0)
head.next = tail
tail.prev = head
total = 0
results = []
def unlink(node):
node.prev.next = node.next
node.next.prev = node.prev
def append_newest(node):
last = tail.prev
last.next = node
node.prev = last
node.next = tail
tail.prev = node
for operation, args in zip(operations, arguments):
if operation == "get":
node = index.get(args[0])
if node is None:
results.append(None)
else:
unlink(node)
append_newest(node)
results.append(node.value)
elif operation == "put":
key, value = args
node = index.get(key)
if node is not None:
total += value - node.value
node.value = value
unlink(node)
append_newest(node)
else:
node = _Node(key, value)
index[key] = node
append_newest(node)
total += value
if len(index) > capacity:
oldest = head.next
unlink(oldest)
del index[oldest.key]
total -= oldest.value
results.append(None)
elif operation == "get_average":
results.append(total / len(index) if index else None)
else:
raise ValueError("unknown operation")
return results