Ranking Frequent Event Names Within a Time Window
Data Structure DesignAuto-graded · 16 test casesLast updated
Simulate a stream of timestamped log events and answer window queries for the k most frequent messages, with ties broken alphabetically, using binary search over a sorted log.
Event Frequency Ranking
You are building a small in-memory event recorder. Events arrive over time, each with an integer timestamp and a text label. At any point you may ask which labels were most common during a given time window.
The recorder is driven by a batch of commands. Write a function that processes the commands in order and returns one result per command.
Commands
You receive two lists of equal length:
operations: each entry is either"log_message"or"get_top_k".arguments: the arguments for the command at the same index.
The two commands are:
"log_message"with arguments[timestamp, message]: record thatmessageoccurred attimestamp. The result for this command isNone."get_top_k"with arguments[start_time, end_time, k]: consider only recorded events whose timestamptsatisfiesstart_time <= t <= end_time(both ends inclusive). Count how many times each distinct message appears among them, then return a list of thekbest messages as described below.
Any other operation name should raise a ValueError.
Ranking Rules
- A message with a higher count comes before one with a lower count.
- If two messages have the same count, the lexicographically smaller message comes first (standard Python string comparison).
- If the window contains fewer than
kdistinct messages, return all of them in the same order. - If the window contains no events, return an empty list.
Queries only see events logged by earlier commands in the same batch.
Output
Return a list with one entry per command: None for each "log_message", and the ranked list of strings for each "get_top_k".
Constraints
1 <= timestamp <= 10^9- Timestamps across
"log_message"commands are non-decreasing in the order they appear. start_time <= end_time1 <= k <= 1001 <= len(message) <= 50- At most
10^5"log_message"commands. - At most
500"get_top_k"commands.
Examples
Example 1
Input: rank_window_events(['log_message', 'log_message', 'log_message', 'log_message', 'log_message', 'log_message', 'get_top_k', 'get_top_k'], [[1, 'error'], [2, 'info'], [3, 'error'], [5, 'warn'], [6, 'info'], [7, 'error'], [1, 5, 2], [4, 7, 3]])
Output: [None, None, None, None, None, None, ['error', 'info'], ['error', 'info', 'warn']]
Example 2
Input: rank_window_events(['get_top_k', 'log_message', 'get_top_k'], [[1, 10, 1], [5, 'only'], [1, 10, 3]])
Output: [[], None, ['only']]
Hints
Hint 1
Because log timestamps never decrease, the events inside any query window form one contiguous block of the log. Think about how to find its two ends without scanning everything.
Hint 2
Use binary search twice: bisect_left for the first timestamp >= start_time, and bisect_right for one past the last timestamp <= end_time. Duplicate timestamps are handled correctly by this left/right pairing.
Hint 3
Count the messages in that block with a hash map, then sort the distinct messages by the key (-count, message) and cut the result to the first k.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Timestamps are non-decreasing, so the log is always sorted by time. Any query window [start_time, end_time] therefore corresponds to one contiguous slice of the log. Two binary searches locate it:
lo = bisect_left(timestamps, start_time)is the first index withtimestamp >= start_time.hi = bisect_right(timestamps, end_time)is one past the last index withtimestamp <= end_time.
Logging is an append to two parallel lists (timestamps and messages). For a query:
- Locate
loandhi. Iflo >= hi, the window is empty and the answer is[]. - Count the messages in
messages[lo:hi]with aCounter. - Sort the distinct messages by the key
(-count, message). - Return the first
k.
Why it is correct
- Every index in
[lo, hi)has a timestamp inside the window, and every index outside violates one bound, so the slice is exactly the set of in-range events. Runs of equal timestamps at either boundary are handled by choosing left for the start and right for the end. - The counter gives exact frequencies in the window.
- The key
(-count, message)is a total order over distinct messages: higher counts first, and equal counts fall back to ascending string order, which is exactly the required tie-break. - Slicing with
[:k]returns every message when there are fewer thank, and an empty window yields[].
Complexity
Let N be the number of logged events, R the number of events in a query window, and U the number of distinct messages in it.
- Logging:
O(1)amortized per command. - Query:
O(log N)to find the slice,O(R)to count,O(U log U)to sort. - Space:
O(N)for the log plusO(U)per query.
In the worst case this is about 500 queries times 10^5 events, or 5 * 10^7 counting steps, which Counter handles quickly since it runs in C.
Reference solution
from bisect import bisect_left, bisect_right
from collections import Counter
from typing import List, Optional
def rank_window_events(operations: List[str], arguments: List[List]) -> List[Optional[List[str]]]:
timestamps: List[int] = []
messages: List[str] = []
results: List[Optional[List[str]]] = []
for operation, args in zip(operations, arguments):
if operation == "log_message":
timestamp, message = args
timestamps.append(timestamp)
messages.append(message)
results.append(None)
elif operation == "get_top_k":
start_time, end_time, k = args
lo = bisect_left(timestamps, start_time)
hi = bisect_right(timestamps, end_time)
if lo >= hi:
results.append([])
continue
counts = Counter(messages[lo:hi])
ranked = sorted(counts, key=lambda m: (-counts[m], m))
results.append(ranked[:k])
else:
raise ValueError("Unknown operation")
return results