Sliding Log Window: Distinct Tags and Dominant Tag Since a Cutoff
Data Structure DesignAuto-graded · 21 test casesLast updated
Replay operations on a bounded, timestamp-ordered log of the newest entries, answering cutoff queries with the distinct key count and the most frequent key (smallest on ties).
Sliding Log Window
A log keeps only the newest capacity entries of a stream. Each entry has an integer timestamp and a string key. Entries are recorded in non-decreasing timestamp order. Whenever recording a new entry would leave the log with more than capacity entries, the entry that was recorded earliest (the oldest by arrival order) is discarded.
You are given a batch of operations to replay, in order, against an initially empty log. Return the answer to every query.
Operations
Each operation is a name plus an argument list.
-
"record_event"with arguments[timestamp, key]: append a new entry with this timestamp and key to the log. Then, if the log holds more thancapacityentries, discard the single oldest one. This operation produces no output. -
"query"with arguments[min_timestamp]: consider only the entries currently in the log whose timestamp is greater than or equal tomin_timestamp(entries whose timestamp equalsmin_timestampdo qualify). Produce the two-element list[distinct_count, top_key]:distinct_countis the number of different keys among the qualifying entries.top_keyis the key that occurs the most times among the qualifying entries (each qualifying entry counts once, so repeated keys add up). If several keys share the highest count,top_keyis the smallest of them in standard string (lexicographic) order.- If no entry in the log qualifies (including when the log is empty), the answer is
[0, ""].
A query does not change the log.
Function
Implement replay_log(capacity, operations, arguments):
capacity(int): the maximum number of entries the log retains.operations(List[str]): operation names, each either"record_event"or"query".arguments(List[List]): same length asoperations;arguments[i]is the argument list foroperations[i], either[timestamp, key](anintand astr) or[min_timestamp](anint).
Return a list with one [distinct_count, top_key] item (an int and a str) per "query" operation, in the order the queries appear. If there are no queries, return an empty list.
The standard library is all you need.
Constraints
1 <= capacity <= 10^51 <= timestamp <= 10^9, and timestamps are non-decreasing across therecord_eventoperationskeyconsists of 1 to 32 lowercase English letters- At most
2 * 10^5record_eventoperations - At most
2000queryoperations - Several entries may share the same timestamp
min_timestampis an arbitrary integer, possibly below or above every retained timestamp- A query issued before any entry has been recorded returns
[0, ""]
Examples
Example 1
Input: replay_log(3, ['record_event', 'record_event', 'record_event', 'query', 'record_event', 'query', 'query'], [[10, 'apple'], [20, 'banana'], [30, 'apple'], [15], [40, 'cherry'], [10], [50]])
Output: [[2, 'apple'], [3, 'apple'], [0, '']]
Hints
Hint 1
Because timestamps never decrease, the entries in the log are sorted by time, so the entries at or after a cutoff form a contiguous suffix of the log.
Hint 2
A deque or a list with a moving head index drops the oldest entry in O(1). For each query you can count keys in the qualifying suffix with a hash map; with at most 2000 queries this is fast enough.
Hint 3
To pick the top key, compare by (-count, key) so that the highest count wins and ties go to the lexicographically smallest key. Entries equal to the cutoff do count.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Two facts drive the solution:
- The log keeps only the newest
capacityentries, so it is a first-in-first-out buffer: append at the end, drop from the front. - Timestamps are non-decreasing, so the retained entries are always sorted by time. The entries with
timestamp >= min_timestamptherefore form a contiguous suffix of the retained entries, and a binary search finds where that suffix begins.
I store timestamps and keys in two parallel lists, plus a head index marking the oldest retained entry. Dropping the oldest entry is just head += 1. When the dead prefix grows to at least half the list (and is reasonably large), I slice it away so memory stays O(capacity).
For a query, bisect_left(times, min_timestamp, head) returns the first retained index whose timestamp is at least the cutoff. If that index is the end of the list, nothing qualifies and the answer is [0, ""]. Otherwise I count the keys in the suffix with a Counter. The number of distinct keys is the size of the counter, and the top key is the minimum by (-count, key), which prefers the highest count and then the lexicographically smallest key.
Why it is correct
- Each recorded entry adds one item, so at most one eviction is needed per insert, and the retained window is always the last
min(total, capacity)entries. - Retained timestamps are sorted and
bisect_leftis used, so every entry at or after the returned index qualifies (including those equal to the cutoff, even when several share a timestamp), and none before it do. The search starts athead, so evicted entries are never seen. - The counter gives exact frequencies over exactly the qualifying entries, and the
(-count, key)ordering implements the stated tie-break. - An empty log or a cutoff above every timestamp gives an index equal to the list length, which returns
[0, ""].
Complexity
record_event: O(1) amortized (compaction costs O(capacity) but happens rarely).query: O(log capacity + k), where k is the number of qualifying entries (k <= capacity). With at most 2000 queries this is about 2 * 10^8 element visits in the worst case, and the counting loop runs in C.- Space: O(capacity) for the log, plus O(k) per query for the counter.
Reference solution
from bisect import bisect_left
from collections import Counter
from typing import List
def replay_log(capacity: int, operations: List[str], arguments: List[List]) -> List[List]:
times: List[int] = []
tags: List[str] = []
head = 0 # index of the oldest retained entry
results: List[List] = []
for op, args in zip(operations, arguments):
if op == "record_event":
timestamp, key = args
times.append(timestamp)
tags.append(key)
if len(times) - head > capacity:
head += 1
# Compact the dead prefix occasionally to keep memory bounded.
if head >= 1024 and head * 2 >= len(times):
times = times[head:]
tags = tags[head:]
head = 0
elif op == "query":
min_timestamp = args[0]
i = bisect_left(times, min_timestamp, head)
if i == len(times):
results.append([0, ""])
else:
counts = Counter(tags[i:])
top_key = min(counts, key=lambda k: (-counts[k], k))
results.append([len(counts), top_key])
else:
raise ValueError("Unknown operation: " + op)
return results