Sliding Window Score Monitor for Support Chats
Data Structure DesignAuto-graded · 18 test casesLast updated
Process a stream of score updates and queries, returning the rolling average and maximum over the latest score of each chat inside a half-open time window.
A support platform scores its chats as they happen. You must simulate a monitor that keeps only recent scores and answers questions about them.
Implement score_window_monitor(window_size, commands, params). It replays a list of commands in order and returns the answers to the query commands.
Commands
commands[i] is one of three strings, and params[i] holds its arguments:
| Command | params[i] | Effect |
|---|---|---|
"record_score" | [timestamp, chat_id, score] | Stores score for chat_id at timestamp. If chat_id already has a record that is still inside the window, the new score and timestamp replace the old ones. |
"get_average_score" | [timestamp] | Returns the mean score of all active chats. |
"get_max_score" | [timestamp] | Returns the highest score among all active chats. |
Rules
- A chat is active at query time
tif its most recent record has timestampswitht - window_size < s <= t. The window is open at the left end and closed at the right end, so a record exactlywindow_sizeseconds old has already expired. - Each chat counts once, using only its latest record. Older records of the same chat are ignored.
- Timestamps never decrease from one command to the next.
- If a chat's earlier record has expired, a new
record_scorefor that chat simply creates a fresh record. get_average_scorereturns a float rounded to 2 decimal places, or0.0if no chat is active.get_max_scorereturns an integer, or-1if no chat is active. A score of0is a real score and is not the same as "no chats".record_scoreproduces no output.
Output
Return a list containing one value per query command (get_average_score or get_max_score), in the order the queries appear.
Constraints
1 <= window_size <= 864001 <= timestamp <= 10^9, and timestamps are non-decreasing across commands1 <= len(chat_id) <= 320 <= score <= 100- At most
100,000commands in total len(commands) == len(params)
Examples
Example 1
Input: score_window_monitor(10, ['record_score', 'record_score', 'get_average_score', 'get_max_score', 'record_score', 'get_average_score', 'get_max_score', 'get_average_score', 'get_max_score'], [[1, 'conv_A', 80], [3, 'conv_B', 90], [5], [5], [8, 'conv_A', 95], [8], [12], [14], [14]])
Output: [85, 90, 92.5, 95, 95, 95]
Example 2
Input: score_window_monitor(1, ['record_score', 'get_average_score', 'get_max_score'], [[5, 'x', 0], [5], [5]])
Output: [0, 0]
Hints
Hint 1
Because timestamps never decrease, the oldest records are always the first to expire. A queue ordered by arrival lets you drop expired records from the front.
Hint 2
A chat can be updated while its older record is still waiting in the queue. When that old entry reaches the front, make sure it does not delete the newer record. Compare timestamps with what is currently stored for that chat.
Hint 3
Keep a running sum and a count of active chats for the average. Scores are only 0 to 100, so a 101-slot tally of how many active chats hold each score gives the maximum with a short scan from the top.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Keep four pieces of state:
latest: a dictionary mapping each chat to its current(score, timestamp). This defines which chats are active.arrivals: a queue of(timestamp, chat_id)pairs, one perrecord_scorecall. Timestamps never decrease, so the queue is sorted by time and the oldest entries are at the front.total: the sum of the scores of all active chats, which gives the average in constant time.tally: an array of 101 counters, wheretally[s]is the number of active chats whose score iss. Scores are limited to 0..100, so the maximum is found by scanning down from 100 to the first non-zero counter.
Before handling any command at time t, drop expired records. Pop entries from the front of arrivals while their timestamp is <= t - window_size. A popped entry removes the chat only if latest[chat] still has that same timestamp. If the chat was updated later, the popped entry is a stale leftover and is ignored.
For record_score, first drop expired records. If the chat is still active, subtract its old score from total and tally. Then store the new record, add it to total and tally, and push it onto the queue.
For get_average_score, return round(total / len(latest), 2), or 0.0 if latest is empty.
For get_max_score, return -1 if latest is empty. Otherwise scan tally from 100 downward to the first non-zero slot. Checking emptiness through latest keeps a real score of 0 distinct from "no chats".
Why it is correct
After dropping expired records at time t, latest holds exactly the chats whose most recent record has a timestamp greater than t - window_size. Records expire in time order because the queue is time-ordered. A chat's current record is removed exactly when its own timestamp reaches the cutoff. Superseded records never remove anything, because their timestamps no longer match the stored one. If a chat is updated twice at the same timestamp, the leftover entry has the same expiry time as the live one, so removing it is still correct. total and tally change only when latest changes, so they always agree with it.
Complexity
- Time: each record enters and leaves the queue once, so expiry is O(1) amortised per command. The maximum scan touches at most 101 slots, which is constant. Overall O(N) for N commands.
- Space: O(N) for the queue and dictionary in the worst case, plus O(101) for the tally.
Reference solution
from collections import deque
from typing import List
def score_window_monitor(window_size: int, commands: List[str], params: List[List]) -> List:
latest = {} # chat_id -> (score, timestamp)
arrivals = deque() # (timestamp, chat_id) in arrival order
tally = [0] * 101 # tally[s] = number of active chats with score s
total = 0
answers = []
def drop_expired(now):
nonlocal total
limit = now - window_size
while arrivals and arrivals[0][0] <= limit:
ts, chat = arrivals.popleft()
cur = latest.get(chat)
if cur is not None and cur[1] == ts:
total -= cur[0]
tally[cur[0]] -= 1
del latest[chat]
for cmd, args in zip(commands, params):
if cmd == "record_score":
ts, chat, score = args
drop_expired(ts)
old = latest.get(chat)
if old is not None:
total -= old[0]
tally[old[0]] -= 1
latest[chat] = (score, ts)
total += score
tally[score] += 1
arrivals.append((ts, chat))
elif cmd == "get_average_score":
drop_expired(args[0])
answers.append(round(total / len(latest), 2) if latest else 0.0)
elif cmd == "get_max_score":
drop_expired(args[0])
best = -1
if latest:
s = 100
while tally[s] == 0:
s -= 1
best = s
answers.append(best)
return answers