Rolling Window Stats: Unique Senders and Peak Message Size
Data Structure DesignAuto-graded · 17 test casesLast updated
Replay a list of operations on a fixed-size sliding window, reporting the distinct sender count and the largest payload size after each insertion.
Rolling Window Stats
A service receives a stream of messages. Each message is a pair (sender_id, size). You must keep track of only the most recent K messages and, after every new message arrives, report two numbers about the messages currently in that window:
- how many different senders appear in it, and
- the largest
sizeamong its messages.
Operation replay
Instead of using a class, your function is given a list of operations and a parallel list of arguments, and it must replay them in order.
"init"with arguments[K]: starts a fresh, empty window of capacityK. Any earlier state is discarded completely. The output for this step isNone."add_event"with arguments[sender_id, size]: appends the message to the window. If the window now holds more thanKmessages, the oldest one is dropped, so that at mostKremain. The output for this step is the list[distinct_senders, max_size], computed on the window after this insertion and any removal.
Return a list with one entry per operation, in the same order as the input.
Details
- A sender counts as present as long as at least one of its messages is still in the window. A sender who appears several times is counted once.
- If fewer than
Kmessages have been added, nothing is dropped. - Every
add_eventis guaranteed to come after at least oneinit. Severalinitoperations may appear; each one fully resets the window.
Constraints
1 <= K <= 200,000- The total number of
add_eventoperations is at most200,000. sender_idis an integer.sizeis a non-negative integer.len(operations) == len(arguments).
Examples
Example 1
Input: rolling_window_stats(['init', 'add_event', 'add_event', 'add_event', 'add_event'], [[3], [1, 10], [2, 20], [1, 5], [3, 15]])
Output: [None, [1, 10], [2, 20], [2, 20], [3, 20]]
Example 2
Input: rolling_window_stats(['init', 'add_event', 'add_event', 'add_event', 'add_event', 'add_event'], [[2], [7, 4], [7, 9], [8, 1], [7, 2], [9, 9]])
Output: [None, [1, 4], [1, 9], [2, 9], [2, 2], [2, 9]]
Example 3
Input: rolling_window_stats(['init', 'add_event', 'add_event'], [[1], [1, 0], [2, 0]])
Output: [None, [1, 0], [1, 0]]
Hints
Hint 1
Treat the two questions separately: one structure for the number of distinct senders, another for the maximum size.
Hint 2
A hash map from sender to its occurrence count, updated on both insertion and eviction, gives the distinct count as the number of keys (remove a key when its count reaches zero).
Hint 3
For the maximum, avoid deleting from the middle: either keep a heap with arrival indices and discard stale tops lazily, or keep a deque of indices whose sizes are in non-increasing order.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
After each insertion the answer needs two independent facts about the last K messages, so each gets its own structure.
Distinct senders. Keep a deque of the messages in arrival order plus a hash map counts from sender to the number of times it appears in the window. On insertion, increment the sender's count. On eviction (popping the oldest message from the deque), decrement its sender's count and delete the key if it reaches zero. The number of distinct senders is len(counts).
Maximum size. Keep a second deque (a monotonic deque) holding (index, size) pairs whose sizes are non-increasing from front to back.
- When a new message arrives, pop from the back while the back's size is
<=the new size, since those messages can never be the maximum again (the new one is at least as large and will outlive them). Then append the new pair. - When the oldest message is evicted, if its index equals the front of the monotonic deque, pop that front too.
- The front of the monotonic deque is always the maximum of the current window.
An "init" clears every structure and the arrival counter.
Why it is correct
- The window deque always holds exactly the last
min(n, K)messages, because each insertion adds one and removes at most one. countsmirrors the window deque exactly, and zero-count keys are removed, so its length is the number of distinct senders.- The monotonic deque contains, in order, every in-window message that is not dominated by a later message with an equal or larger size. The overall maximum of the window is never dominated, so it is at the front. Since evictions happen in arrival order, an expired message can only be at the front, so removing it by index match keeps the structure valid.
- The newest message is always in the window and in the monotonic deque, so the answer is never read from an empty structure.
Complexity
Each message is pushed and popped at most once in every structure, so the work is O(1) amortized per add_event, O(N) overall. Space is O(K).
Reference solution
from collections import Counter, deque
from typing import List, Optional
def rolling_window_stats(operations: List[str], arguments: List[List[int]]) -> List[Optional[List[int]]]:
results = []
window = deque() # (index, sender, size) in arrival order
counts = Counter() # sender -> occurrences in window
mono = deque() # (index, size), sizes non-increasing front to back
k = None
next_index = 0
for op, args in zip(operations, arguments):
if op == "init":
k = args[0]
window.clear()
counts.clear()
mono.clear()
next_index = 0
results.append(None)
elif op == "add_event":
sender, size = args
index = next_index
next_index += 1
window.append((index, sender, size))
counts[sender] += 1
while mono and mono[-1][1] <= size:
mono.pop()
mono.append((index, size))
if len(window) > k:
old_index, old_sender, _ = window.popleft()
counts[old_sender] -= 1
if counts[old_sender] == 0:
del counts[old_sender]
if mono and mono[0][0] == old_index:
mono.popleft()
results.append([len(counts), mono[0][1]])
return results