Rolling Mean of Payload Lengths Over a 60-Second Event Window
Data Structure DesignAuto-graded · 15 test casesLast updated
Process a stream of checksummed events with duplicates and out-of-order timestamps, reporting a running average payload length over a 60-second window using a queue, a set and a running sum.
You are given a list of events that arrive one after another, possibly with timestamps out of order. After each event is handled, report the average payload length of the events currently counted in a 60-second window.
Each event is a dictionary with these keys:
id: an identifier (string)timestamp: an integer number of secondspayload: a stringchecksum: a string
Write windowed_payload_mean(events), which returns a list with exactly one float per input event. Entry i is the average payload length right after event i has been processed.
Processing rules
Keep these pieces of state:
- A clock, initially unset.
- A window queue of accepted events, ordered by arrival (not by timestamp). Each entry stores its timestamp, id and payload length.
Handle each event in order:
-
Checksum. The event is valid only if
checksumis exactly equal topayload(string equality). An invalid event is ignored completely: the clock does not change and nothing is removed or added. The current average is still reported. -
Advance the clock. For a valid event, set
clock = max(clock, timestamp). This happens for every valid event, even one that is later rejected as late or as a duplicate. If the clock was unset, it becomes this event's timestamp. -
Expire. Let
cutoff = clock - 60. Look at the front (oldest arrival) of the window queue. While the front entry has a timestamp strictly less thancutoff, remove it. Stop at the first front entry that is not expired, even if entries behind it have older timestamps. Removed entries no longer count, and their ids are free to be accepted again. -
Admit. Append the current event to the back of the queue only if both hold:
timestamp >= cutoff(an event exactly 60 seconds behind the clock is still accepted), and- its
idis not currently held by any entry in the window queue.
Otherwise the event is discarded. When an id is accepted, the first copy wins, and a later copy with a different payload does not replace it.
-
Report. Append to the result the sum of payload lengths in the queue divided by the number of entries in the queue, or
0.0if the queue is empty.
An empty payload with an empty checksum is valid and has length 0.
Constraints
0 <= len(events) <= 10^5- Timestamps are integers and may be negative or repeated.
- Every event contains all four keys.
- The result must be computed in at most
O(n log n)time overall. - Return an empty list for empty input.
Examples
Example 1
Input: windowed_payload_mean([{'id': 'a', 'timestamp': 0, 'payload': 'hi', 'checksum': 'hi'}, {'id': 'b', 'timestamp': 30, 'payload': 'world', 'checksum': 'world'}, {'id': 'c', 'timestamp': 61, 'payload': 'x', 'checksum': 'x'}])
Output: [2, 3.5, 3]
Example 2
Input: windowed_payload_mean([{'id': 'a', 'timestamp': 10, 'payload': 'ok', 'checksum': 'bad'}, {'id': 'b', 'timestamp': 20, 'payload': 'yes', 'checksum': 'yes'}])
Output: [0, 3]
Hints
Hint 1
Keep a running total of payload lengths and a count of queued entries so each average is O(1) to compute instead of rescanning the window.
Hint 2
Use a deque ordered by arrival plus a set of ids currently in the deque. Whenever you pop an entry from the front, also remove its id from the set and subtract its length from the total.
Hint 3
Expiry only inspects the front of the deque and stops at the first non-expired entry, even if later entries are older. Invalid events must skip the clock update, but still output the current average.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Process the events in a single pass, maintaining:
clock: the largest timestamp among checksum-valid events seen so far.window: a deque of(timestamp, id, length)entries in arrival order.live_ids: a set containing exactly the ids that are inwindow.total: the sum of the lengths inwindow.
For each event:
- If the checksum differs from the payload, change nothing and output the current average (
total / len(window), or0.0when empty). - Otherwise, raise the clock to
max(clock, timestamp). - Compute
cutoff = clock - 60and pop from the front of the deque while the front timestamp is belowcutoff. For each popped entry, subtract its length fromtotaland remove its id fromlive_ids. - Admit the event (append, add the id, add its length) if its timestamp is at least
cutoffand its id is not inlive_ids. - Output the current average.
Why it is correct
- The state always reflects the rules:
totalchanges by the same length on every append and pop, so it equals the sum over the queue.live_idsis added to on append and removed from on pop, so it matches the queue's ids exactly. This makes the duplicate check scoped to the live window, as required. - The clock moves only on valid events, including those later discarded as late or duplicate, which matches the rules.
- The queue is ordered by arrival, and expiry stops at the first non-expired front entry. An out-of-order entry sitting behind a newer one therefore stays counted until everything ahead of it expires. This is the behavior the statement defines, and the code follows it directly.
- The boundary is inclusive: expiry removes only entries with
timestamp < cutoff, and admission needstimestamp >= cutoff.
If strict event-time eviction were required instead, a min-heap keyed by timestamp would give O(log n) per event, which still fits the O(n log n) bound. The rules here specify the arrival-order behavior, so the deque is used.
Complexity
- Time: O(n). Each event is appended at most once and popped at most once, and the set operations are O(1) on average.
- Space: O(w), where w is the number of entries in the window (at most n).
Reference solution
from collections import deque
from typing import Dict, List
def windowed_payload_mean(events: List[Dict[str, object]]) -> List[float]:
clock = None
window = deque() # (timestamp, id, length) in arrival order
live_ids = set() # ids currently in window
total = 0 # sum of lengths in window
result = []
for ev in events:
payload = ev["payload"]
if ev["checksum"] != payload:
result.append(total / len(window) if window else 0.0)
continue
ts = ev["timestamp"]
if clock is None or ts > clock:
clock = ts
cutoff = clock - 60
while window and window[0][0] < cutoff:
_, old_id, old_len = window.popleft()
total -= old_len
live_ids.remove(old_id)
if ts >= cutoff and ev["id"] not in live_ids:
live_ids.add(ev["id"])
window.append((ts, ev["id"], len(payload)))
total += len(payload)
result.append(total / len(window) if window else 0.0)
return result