KatInterview

Deduplicate Repeated Log Messages with Time Window

Data Structure DesignAuto-graded · 17 test cases
MediumAuto-gradedData Structure Designhash-mapstreamingrate-limiting

Last 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:

  1. The first occurrence of any message is always included in the output.
  2. 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.
  3. Messages that are filtered out (suppressed) must not affect the "last included" timestamp for future comparisons.
  4. Message matching is case-sensitive: "Error" and "error" are treated as different messages.
  5. 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 timestamp in non-decreasing order.

Returns

  • A list of log entries (in the same format as the input) that pass the filtering rules.

Constraints

  • 1 <= len(logs) <= 10^5
  • 0 <= timestamp <= 10^9
  • The input is sorted by timestamp in non-decreasing order
  • 1 <= len(message) <= 100
  • Each message consists 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