Deduplicate Repeated Log Messages with Time Window
Data Structure DesignAuto-graded · 17 test casesLast updated
Filter a time-ordered stream of log messages to show each distinct message only once per 10-second window
Problem Statement
You are building a log aggregation system that receives timestamped messages from distributed services. To reduce noise and prevent duplicate alerts, the system should suppress repeated messages that arrive within a short time window.
Write a function that filters a chronologically ordered sequence of log entries. Each entry is a pair containing an integer timestamp (seconds since epoch) and a string message.
Apply these filtering rules:
- The first occurrence of any message is always included in the output.
- A subsequent occurrence of the same message is included only if strictly more than 10 seconds have elapsed since that message was last included in the output.
- Messages that are filtered out (suppressed) must not affect the "last included" timestamp for future comparisons.
- Message matching is case-sensitive:
"Error"and"error"are treated as different messages. - The output must maintain the original chronological order of included entries.
Function Signature
def deduplicate_logs(logs: List[List]) -> List[List]:
pass
Parameters
logs: A list of log entries, where each entry is a two-element list[timestamp, message].- The entries are sorted by
timestampin non-decreasing order.
- The entries are sorted by
Returns
- A list of log entries (in the same format as the input) that pass the filtering rules.
Constraints
1 <= len(logs) <= 10^50 <= timestamp <= 10^9- The input is sorted by timestamp in non-decreasing order
1 <= len(message) <= 100- Each
messageconsists of printable ASCII characters
Examples
Example 1
Input: deduplicate_logs([[1, 'LOW_BATTERY'], [5, 'LOW_BATTERY'], [11, 'LOW_BATTERY'], [12, 'LOW_BATTERY']])
Output: [[1, 'LOW_BATTERY'], [12, 'LOW_BATTERY']]
Example 2
Input: deduplicate_logs([[0, 'OBSTACLE_DETECTED'], [3, 'Path_Blocked'], [4, 'PATH_BLOCKED'], [10, 'OBSTACLE_DETECTED'], [11, 'OBSTACLE_DETECTED']])
Output: [[0, 'OBSTACLE_DETECTED'], [3, 'Path_Blocked'], [4, 'PATH_BLOCKED'], [11, 'OBSTACLE_DETECTED']]
Hints
Hint 1
Use a hash map to track the last timestamp at which each distinct message was included in the output
Hint 2
Remember that suppressed messages should not update the tracking state
Hint 3
The comparison must be strictly greater than 10, not greater-or-equal
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires tracking the last output timestamp for each distinct message independently. A hash map provides O(1) lookup and update for each message key.
The algorithm processes each log entry in chronological order:
- Check if the message has been included before by looking it up in the hash map
- If the message is new (not in the map), include it and record its timestamp
- If the message exists, compute the time difference between the current timestamp and the last included timestamp
- Include the entry only if the difference is strictly greater than 10 seconds
- When an entry is included, update the hash map with the new timestamp
- When an entry is suppressed, leave the hash map unchanged
The critical insight is that suppressed entries must not update the tracking state. If they did, a burst of repeated messages within the window could incorrectly reset the timer, preventing later valid entries from being included.
Why This Works
The hash map maintains an invariant: after processing any prefix of the input, last_included[m] holds the timestamp of the most recent occurrence of message m that was added to the output. If m never appeared in the output, it is absent from the map.
Each decision depends only on whether the message appeared in prior output and, if so, when. The map provides exactly this information. Since we process entries in timestamp order and append to the result list, the output preserves chronological order automatically.
Message strings serve directly as hash keys. Python's string equality and hashing are case-sensitive by default, so "Error" and "error" map to different buckets with no additional code.
Complexity Analysis
- Time: O(n · L) where n is the number of log entries and L is the maximum message length. Hashing each message costs O(L). Since L ≤ 100 is bounded, this simplifies to O(n).
- Space: O(d · L) for the hash map where d is the number of distinct messages, plus O(n) for the output list in the worst case when all entries pass the filter.
Implementation
from typing import List
def deduplicate_logs(logs: List[List]) -> List[List]:
TIME_WINDOW = 10
last_included = {}
filtered = []
for timestamp, message in logs:
if message not in last_included or timestamp - last_included[message] > TIME_WINDOW:
filtered.append([timestamp, message])
last_included[message] = timestamp
return filtered
Edge Cases to Consider
- Timestamp zero: Using
if not last_included.get(message)would incorrectly treat timestamp 0 as "never seen" because 0 is falsy in Python. Always check membership explicitly within. - Exact 10-second boundary: When the difference equals exactly 10, the entry must be suppressed. The condition must use
>not>=. - Identical consecutive timestamps: If the same message appears twice at the same timestamp, the second occurrence has difference 0 and is suppressed.
- Case sensitivity: No normalization should be applied.
"WARNING"and"warning"are distinct and tracked separately.