Rolling Read/Write Rate Tracker for an In-Memory Dictionary Store
Data Structure DesignAuto-graded · 17 test casesLast updated
Simulate a key-value store that logs reads and writes with timestamps and answers per-second average rate queries over trailing windows, using compact time buckets.
Rolling Read/Write Rate Tracker
You are building a small in-memory key-value store that also measures how busy it is. Besides storing and fetching values, it must report the average number of reads and writes per second over a trailing time window.
Because the store is driven by a single function call, you are given a list of operation names and a parallel list of argument lists. Process them in order, as if calling methods on one fresh store, and return one result per operation.
Operations
Each operations[i] is one of the following, with its parameters in arguments[i]:
"put"with[key, value, timestamp]: storesvalueunderkey, replacing any existing value, and records one write event attimestamp. Result:None."get"with[key, timestamp]: records one read event attimestamp, then returns the value stored forkey, orNoneif the key does not exist. The read event is recorded even when the key is missing."average_gets"with[window_seconds, timestamp]: returns the number of read events whose time lies in the inclusive range[timestamp - window_seconds + 1, timestamp], divided bywindow_seconds."average_puts"with[window_seconds, timestamp]: same as above, but for write events.
Any other operation name must raise ValueError.
Rules
- Timestamps are integer seconds and never decrease from one operation to the next (across all operation types).
- The divisor is always exactly
window_seconds, regardless of how much history exists. Seconds before the first event, or before time 0, simply contain no events but still count in the divisor. - Several events may share the same timestamp; all of them count.
- Overwriting a key still counts as a write. Reading a missing key still counts as a read.
- A window with no matching events yields
0.0(a numeric zero). - Memory should grow with the number of distinct seconds that had activity, not with the raw number of operations.
Function
Implement metrics_kv_store(operations, arguments) returning the list of results, one per operation, in order.
Constraints
1 <= len(key), len(value) <= 1001 <= timestamp <= 2 * 10^91 <= window_seconds <= 604800- At most
2 * 10^5operations in total. - Timestamps are non-decreasing across the whole sequence.
Examples
Example 1
Input: metrics_kv_store(['put', 'put', 'get', 'average_gets', 'average_puts', 'average_puts'], [['a', '1', 10], ['b', '2', 10], ['a', 15], [10, 15], [10, 15], [5, 16]])
Output: [None, None, '1', 0.1, 0.2, 0]
Hints
Hint 1
Treat the storage and the statistics as two independent pieces: a dictionary for the data, and one event log per kind of operation (reads and writes).
Hint 2
Since time never goes backwards, events at the same second can be merged into a single [second, count] bucket at the end of a deque. This keeps memory tied to distinct active seconds.
Hint 3
No query reaches back more than 604800 seconds, so buckets older than timestamp - 604800 + 1 can be dropped from the front. To answer a query, add up the counts of buckets inside the window and divide by window_seconds, not by the number of active seconds.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Split the problem into two independent parts.
- Data storage: a plain dictionary.
putoverwrites,getusesdict.get, which naturally returnsNonefor missing keys. - Rate metrics: one deque for read events and one for write events. Each deque holds
[second, count]buckets in increasing order of second.
Because timestamps never decrease, a new event either falls in the same second as the last bucket (increment its count) or in a later second (append a new bucket). A burst of many operations in one second therefore costs only one bucket, so memory depends on the number of distinct active seconds.
Pruning. No query looks back more than 604800 seconds. Before handling each operation we pop buckets from the front whose second is below timestamp - 604800 + 1. Later operations have timestamps at least as large, so a discarded bucket can never be needed again.
Querying. For average_gets / average_puts, compute start = timestamp - window_seconds + 1, sum the counts of buckets with start <= second <= timestamp, and divide by window_seconds. The divisor is always the full window length, so empty windows give 0.0 and windows reaching before the first event or before time 0 need no special handling.
Why it is correct
- The deque stays sorted by second, and each second has at most one bucket, so every event is counted exactly once.
- Reads are recorded even on a miss and writes even on an overwrite, as required.
- Pruning only removes buckets outside every possible current and future window.
- Dividing by
window_secondsmatches the specified definition.
Complexity
Let B be the number of buckets currently held (at most 604800) and K the number of distinct keys.
put/get: amortized O(1), since each bucket is added once and removed at most once.average_*: O(B) for the scan. (Storing prefix counts and binary searching would make this O(log B).)- Space: O(K + B).
Reference solution
from collections import deque
from typing import List
def metrics_kv_store(operations: List[str], arguments: List[List]) -> List[object]:
store = {}
get_events = deque() # [second, count] buckets, increasing by second
put_events = deque()
results = []
max_window = 604800
def prune(timestamp):
cutoff = timestamp - max_window + 1
while get_events and get_events[0][0] < cutoff:
get_events.popleft()
while put_events and put_events[0][0] < cutoff:
put_events.popleft()
def record(events, timestamp):
if events and events[-1][0] == timestamp:
events[-1][1] += 1
else:
events.append([timestamp, 1])
for operation, args in zip(operations, arguments):
if operation == "put":
key, value, timestamp = args
prune(timestamp)
store[key] = value
record(put_events, timestamp)
results.append(None)
elif operation == "get":
key, timestamp = args
prune(timestamp)
record(get_events, timestamp)
results.append(store.get(key))
elif operation in ("average_gets", "average_puts"):
window_seconds, timestamp = args
prune(timestamp)
events = get_events if operation == "average_gets" else put_events
start = timestamp - window_seconds + 1
count = sum(n for t, n in events if start <= t <= timestamp)
results.append(count / window_seconds)
else:
raise ValueError("Unknown operation")
return results