You are building a real-time analytics system that must detect the top-K most-frequently-appearing keys
(e.g., user IDs, events, or topics) within a rolling time window.
Given a stream of events as a list of tuples:
events: List[Tuple[int, str]] # (unix_timestamp, key)
Implement:
def top_k_frequent_in_window(
events: List[Tuple[int, str]],
window_size: int,
k: int
) -> List[Tuple[str, int]]:
"""
Returns a list of (key, frequency) for the top-K most frequent keys
within each sliding window of window_size seconds.
Text
Events are NOT guaranteed to be sorted by timestamp.
Windows are fixed (tumbling) windows of window_size seconds starting
at the earliest event timestamp.
Return one (key, frequency) pair per top-K key per window.
If frequencies tie within a window, prefer the alphabetically smaller key.
Order the final combined result by key alphabetically.
"""
Constraints:
- Events list can contain up to 1 million entries
- Timestamps span up to 30 days
- Optimize for O(n log n) or better
- Use only standard library (collections allowed)
Input Format:
Line 1: window_size k
Line 2: n (number of events)
Lines 3 to n+2: timestamp key
Output Format:
One line per (key, frequency) pair in the result, space-separated
Order by key alphabetically