Duplicate Log Suppression Within a Cooldown Window
Data Structure DesignAuto-graded · 18 test casesLast updated
Simulate a duplicate-log filter driven by an operation script, tracking per-message cooldowns where only accepted messages restart the timer.
Duplicate Log Suppression
A logging pipeline receives log lines, each with an integer timestamp (in seconds). To avoid flooding, it suppresses repeated identical lines that arrive too soon after the last one it let through.
The behavior of the filter is described as a script of operations, and your function must replay the script and report the result of each step.
The filter
- Creating the filter sets a cooldown length
window(in seconds). - Submitting a line
(timestamp, message)yields a decision:- Accept (
True) if this exactmessagestring has never been accepted before, or iftimestamp - last_accepted_time >= window, wherelast_accepted_timeis the timestamp of the most recent accepted submission of that same string. - Reject (
False) otherwise.
- Accept (
- Accepting a line records its
timestampas the newlast_accepted_timefor that string. - Rejecting a line changes nothing. A rejected timestamp never restarts or extends a cooldown.
- Different message strings are fully independent of each other. Several different messages may share the same timestamp, and the same message may be submitted more than once at one timestamp.
- Message comparison is exact and case-sensitive.
Your task
Implement replay_filter(operations, arguments).
operationsis a list of strings. Each is either"MessageLimiter"(create the filter) or"should_accept_message"(submit a line).argumentsis a list of the same length. For"MessageLimiter", the entry is[window], or an empty list[], in which casewindowis10. For"should_accept_message", the entry is[timestamp, message].- Return a list of the same length as
operations. The entry for a creation step isNone; the entry for a submission isTrueorFalseper the rules above. - If
"MessageLimiter"appears again later in the script, it creates a fresh filter: the new window applies and all earlier history is forgotten. - Submissions that appear before any creation step are treated as using a filter with
window = 10and empty history. - Any other operation name should raise
ValueError.
Constraints
1 <= window <= 10^60 <= timestamp <= 10^9- Timestamps across successive submissions are non-decreasing.
1 <= len(message) <= 50- At most
10^5submissions in a script. len(operations) == len(arguments)
Examples
Example 1
Input: replay_filter(['MessageLimiter', 'should_accept_message', 'should_accept_message', 'should_accept_message', 'should_accept_message', 'should_accept_message'], [[10], [1, 'foo'], [2, 'bar'], [3, 'foo'], [8, 'bar'], [10, 'foo']])
Output: [None, True, True, False, False, False]
Example 2
Input: replay_filter(['MessageLimiter', 'should_accept_message', 'should_accept_message', 'should_accept_message', 'should_accept_message'], [[5], [0, 'a'], [5, 'a'], [6, 'a'], [10, 'a']])
Output: [None, True, True, False, True]
Example 3
Input: replay_filter(['MessageLimiter', 'should_accept_message', 'should_accept_message', 'should_accept_message', 'should_accept_message', 'should_accept_message'], [[], [7, 'x'], [7, 'y'], [7, 'x'], [17, 'x'], [17, 'y']])
Output: [None, True, True, False, True, True]
Hints
Hint 1
For each distinct message you only need one number: when it was last accepted (or the earliest time it may be accepted again).
Hint 2
Only update that stored number when a submission is accepted. Updating on rejections would let a steady stream of repeats block a message forever.
Hint 3
The boundary is inclusive: a gap of exactly `window` is allowed. Use `in` or `.get(...) is None` to detect unseen messages, not a truthiness check, since timestamp 0 is valid.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Each message's decision depends only on when that exact string was last accepted. Keep a dictionary mapping each message to its last accepted timestamp, and walk through the script once.
- On a creation step, store the window (default 10 if no argument is given), clear the dictionary, and output
None. - On a submission, look up the message. If it is absent, or
timestamp - last >= window, accept it, record the new timestamp, and outputTrue. Otherwise outputFalseand leave the dictionary untouched. - Any other operation name raises
ValueError.
Why it is correct
The rule says a message is accepted when at least window seconds have passed since its last accepted occurrence. The dictionary invariant is that each entry always holds the most recent accepted timestamp of its message. That holds because only accepted submissions write to it, and each such write stores the current (newest) timestamp. Rejected submissions never write, so they cannot extend a cooldown. Messages never share entries, so identical timestamps across different messages cause no interference. The >= comparison makes the boundary inclusive, and checking prev is None rather than truthiness correctly handles a first acceptance at timestamp 0.
For instance, with window 5 and message "a": accepted at 0, accepted at 5 (gap exactly 5), rejected at 6 (gap 1 from 5), accepted at 10 (gap 5 from 5).
Complexity
- Time: O(n) for n steps, with O(1) average dictionary work per step (hashing is bounded by the 50-character message length).
- Space: O(U), where U is the number of distinct accepted messages.
Reference solution
from typing import List
def replay_filter(operations: List[str], arguments: List[List]) -> List:
last_accepted = {}
window = 10
results = []
for op, args in zip(operations, arguments):
if op == "MessageLimiter":
window = args[0] if args else 10
last_accepted = {}
results.append(None)
elif op == "should_accept_message":
timestamp, message = args
prev = last_accepted.get(message)
accepted = prev is None or timestamp - prev >= window
if accepted:
last_accepted[message] = timestamp
results.append(accepted)
else:
raise ValueError("unknown operation")
return results