Sliding-Window Leaderboard Replay Simulator
Data Structure DesignAuto-graded · 18 test casesLast updated
Simulate a class that logs timestamped events and reports the K most frequent IDs in a closed time window, with out-of-order events and queries.
Sliding-Window Leaderboard Replay Simulator
A leaderboard service counts how often string IDs appear in a stream of timestamped events. At any moment it can report which IDs were most frequent in a recent time window.
You are given a script of method calls on this service. Write a function that replays the script and returns the result of every call.
The service
The service supports three operations, identified by these exact names:
"TopTracker"takes[window_size_ms, k]. It sets up the service with a window length (in milliseconds) and the number of IDs to report. It discards all previously stored events and replaces the old settings."record_event"takes[entity_id, timestamp_ms]. It stores one occurrence ofentity_idat timetimestamp_ms."get_top_k"takes[current_timestamp_ms]. It returns a list of at mostkIDs ranked as described below.
Ranking rules
For a get_top_k call with query time t, the window is the closed interval [t - window_size_ms, t]. An event counts if its timestamp lies in this interval, endpoints included.
- An ID's frequency is the number of stored events for that ID inside the window. Several events with the same ID and the same timestamp each count separately.
- IDs with frequency 0 are never reported.
- Sort by frequency, highest first. If frequencies are equal, the lexicographically smaller ID comes first.
- Return the first
kIDs of that order. If fewer thankIDs qualify, return all of them. If none qualify, return[].
Events can be recorded in any timestamp order, and queries can be made in any time order. A query never changes the stored data. An event with a timestamp later than t is ignored by that query, but it stays stored for later queries.
Function
operations and arguments have the same length, and arguments[i] holds the argument list for operations[i]. Return a list of the same length. Each entry is None for "TopTracker" and "record_event", and a list of ID strings for "get_top_k".
Constraints
operationsandargumentshave equal length, and every operation name is one of the three above."TopTracker"is the first operation in every script, though it may appear again later to reset the service.window_size_ms >= 0andk >= 1.- Timestamps are integers and may arrive in any order.
- IDs are non-empty strings, compared by ordinary string ordering.
- A
get_top_kcall should not rescan every stored event. Aim to be faster than a full scan of the history.
Examples
Example 1
Input: replay_window_leaderboard(['TopTracker', 'record_event', 'record_event', 'record_event', 'get_top_k'], [[1000, 2], ['A', 1000], ['B', 1200], ['A', 1500], [1800]])
Output: [None, None, None, None, ['A', 'B']]
Example 2
Input: replay_window_leaderboard(['TopTracker', 'get_top_k', 'record_event', 'record_event', 'get_top_k'], [[100, 3], [1000], ['x', 900], ['y', 899], [1000]])
Output: [None, [], None, None, ['x']]
Example 3
Input: replay_window_leaderboard(['TopTracker', 'record_event', 'record_event', 'record_event', 'record_event', 'get_top_k'], [[10, 3], ['b', 0], ['a', 0], ['c', 0], ['a', 10], [10]])
Output: [None, None, None, None, None, ['a', 'b', 'c']]
Hints
Hint 1
Think about whether you can ever discard an event. If query times can go backward, an event that is outside one window may be needed by a later query.
Hint 2
Store, for each ID, a list of its timestamps kept in sorted order. The number of events in a closed range is then the difference of two binary-search positions.
Hint 3
Use bisect_left for the lower end and bisect_right for the upper end so both endpoints are included. Rank the IDs with the key (-count, id) so ties go to the smaller ID.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Because both events and queries can arrive with any timestamp, nothing can ever be thrown away. Evicting old events, as in the usual sliding-window queue, would break a later query whose time is earlier than a previous one.
So the solution keeps the full history in a form that supports fast range counting:
- Storage. Keep a dictionary from ID to a sorted list of timestamps. A new event is inserted at its sorted position, found with
bisect_right. This keeps the list sorted even when events arrive out of order, and duplicate timestamps are kept. - Counting. For a query at time
t, the window is[t - window, t]. For one ID, the number of timestamps in this closed range isbisect_right(list, t) - bisect_left(list, t - window).bisect_leftgives the first index with value>= low, andbisect_rightgives the index just past the last value<= t, so both endpoints are included. - Ranking. Collect
(-count, id)for every ID with a positive count and sort. Tuples compare element by element, so the highest count comes first and ties go to the lexicographically smaller ID. Slice the firstkentries and keep only the IDs. - Reset. Each
"TopTracker"call overwrites the window andkand clears all stored events.
Why it is correct
- Each per-ID list is always sorted, so the binary searches are valid.
- Queries never modify state, so each one sees the full history regardless of query order.
- Events later than
tare excluded bybisect_right(list, t), and events beforet - windoware excluded bybisect_left. - The sort key encodes exactly the required order: frequency descending, then ID ascending. Slicing handles fewer than
kqualifying IDs and an empty window.
Complexity
Let U be the number of distinct IDs, n_e the number of events of one ID, and m the number of IDs active in the window.
record_event:O(log n_e)to find the position plusO(n_e)worst case for the list insertion (cheap when events arrive mostly in order).get_top_k:O(U log n_max + m log m).- Space:
O(N)forNstored events.
Reference solution
from bisect import bisect_left, bisect_right
from typing import List
def replay_window_leaderboard(operations: List[str], arguments: List[List]) -> List:
window = None
k = None
times_by_id = {}
output = []
for op, args in zip(operations, arguments):
if op == "TopTracker":
window, k = args
times_by_id = {}
output.append(None)
elif op == "record_event":
entity_id, ts = args
lst = times_by_id.setdefault(entity_id, [])
pos = bisect_right(lst, ts)
lst.insert(pos, ts)
output.append(None)
elif op == "get_top_k":
t = args[0]
low = t - window
ranked = []
for entity_id, lst in times_by_id.items():
cnt = bisect_right(lst, t) - bisect_left(lst, low)
if cnt > 0:
ranked.append((-cnt, entity_id))
ranked.sort()
output.append([e for _, e in ranked[:k]])
return output