LRU Store with Rolling Mean Over Recent Writes
Data Structure DesignAuto-graded · 14 test casesLast updated
Simulate a batch of operations on an LRU key-value store that also tracks a rolling mean of the last k written values, with O(1) per operation.
Task
Simulate a single object that keeps two independent pieces of state and report the results of a list of operations.
- A bounded LRU store. It holds at most
capacitykey-value pairs. When a write would make it hold more thancapacitykeys, the least recently used key is removed. - A rolling mean. It tracks the last
kvalues that were ever written, and can report their mean.
You are given operations and arguments of equal length. Process them in order. operations[i] is one of the following, and arguments[i] holds its arguments.
| Operation | Arguments | Effect | Output entry |
|---|---|---|---|
"put" | [key, value] | Store value under key, mark key as most recently used, and append value to the stream of written values. If the store now holds more than capacity keys, remove the least recently used key. | None |
"get" | [key] | If key is present, mark it as most recently used and return its value. Otherwise change nothing. | The value, or -1 if the key is absent |
"getMovingAverage" | [] | Compute the mean of the last k values written (or all of them, if fewer than k have been written). | A float, or 0.0 if no value has been written yet |
Return a list with exactly one output entry per operation, in order.
Rules to be careful about
- Both
putand a successfulgetcount as a "use" of a key. - Writing to a key that already exists replaces its value and refreshes its recency. It never causes an eviction by itself.
- The rolling mean is based on the stream of written values, not on the contents of the store. Every
putcontributes its value, including overwrites of existing keys. Evicting a key does not remove its value from the stream. - Before
kvalues have been written, divide by the number of values written so far, not byk. - A
getfor a missing key does not alter any state.
Function
Implement stream_processor(capacity, k, operations, arguments) returning the list of outputs described above.
Constraints
capacityandkare positive integers.operationsandargumentshave the same length.- Every operation name is one of
"put","get","getMovingAverage". - Keys and values are integers.
- Each operation should run in O(1) time.
Examples
Example 1
Input: stream_processor(2, 3, ['put', 'put', 'getMovingAverage', 'put', 'getMovingAverage', 'put', 'get', 'getMovingAverage'], [[1, 10], [2, 20], [], [3, 30], [], [4, 40], [1], []])
Output: [None, None, 15, None, 20, None, -1, 30]
Example 2
Input: stream_processor(1, 2, ['getMovingAverage', 'put', 'put', 'get', 'getMovingAverage'], [[], [7, 5], [7, 9], [7], []])
Output: [0, None, None, 9, 7]
Hints
Hint 1
The two features only share the put operation. Keep the key-value store and the window of recent values as completely separate structures.
Hint 2
For the store, you need O(1) lookup plus O(1) reordering and removal of the oldest-used key. A hash map combined with a doubly linked list, or an ordered dictionary, does this.
Hint 3
For the mean, keep a queue of the last k values and a running sum. On each put, add the new value, and if the queue grows beyond k, remove the oldest value and subtract it. Divide by the current queue length, and return 0.0 if it is empty.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The object has two independent pieces of state that meet only at put, so we keep them as two separate structures.
LRU store. Use an ordered hash map, which is a hash map whose entries are linked in a doubly linked list. Keep the least recently used key at the front and the most recently used at the back.
put: if the key exists, remove it first so reinserting places it at the back. Insert the pair. If the size now exceedscapacity, pop the front entry.get: if the key is missing, return-1. Otherwise move it to the back and return its value.
Rolling mean. Keep a queue of the most recent written values and their running sum.
- On every
put, append the value and add it to the sum. If the queue length exceedsk, pop the oldest value and subtract it from the sum. - The mean is
sum / len(queue), or0.0when the queue is empty. Dividing by the queue length rather thankhandles the warm-up phase.
Why it is correct
- Every touch (
putor successfulget) moves a key to the back, and untouched keys keep their relative order. So the front is always the least recently used key. Eviction only happens when the size exceedscapacity, so the store never holds more thancapacitykeys. An overwrite reinserts the same key, so the size does not grow and nothing is evicted. - After each
put, the queue holds exactly the lastmin(n, k)written values, wherenis the number of puts so far, and the running sum equals their total. Each step adds the new value and removes exactly the one that slid out. Because the queue is fed by everyputand never touched by evictions, overwrites count and evicted keys' values stay in the window, as required.
Complexity
- Time: O(1) per operation, so O(n) for n operations.
- Space: O(capacity + k).
Reference solution
from collections import OrderedDict, deque
from typing import List, Optional
def stream_processor(capacity: int, k: int, operations: List[str], arguments: List[List[int]]) -> List[Optional[float]]:
store = OrderedDict() # least recently used key at the front
recent = deque() # last k written values
running_sum = 0
output = []
for op, args in zip(operations, arguments):
if op == "put":
key, value = args
if key in store:
del store[key]
store[key] = value
if len(store) > capacity:
store.popitem(last=False)
recent.append(value)
running_sum += value
if len(recent) > k:
running_sum -= recent.popleft()
output.append(None)
elif op == "get":
key = args[0]
if key not in store:
output.append(-1)
else:
store.move_to_end(key)
output.append(store[key])
elif op == "getMovingAverage":
output.append(running_sum / len(recent) if recent else 0.0)
else:
raise ValueError("unknown operation")
return output