KatInterview

Sliding Window Event Log with Time-Based Expiration

Data Structure DesignAuto-graded · 15 test cases
MediumAuto-gradedData Structure Designsliding-windowqueuestime-series

Last updated

Design a data structure that tracks timestamped events and supports queries over a moving time window with automatic expiration of old entries.

Design a data structure that maintains a log of timestamped events and supports queries constrained to a sliding time window. The structure should automatically discard events that fall outside the current window.

You will implement a system that processes a sequence of operations on an event log. Each operation is one of:

  • record: Add a new event to the log with the current timestamp
  • count: Return how many events are currently within the time window
  • recent: Return all events currently within the time window, in chronological order

The time window has a fixed duration specified at initialization. An event recorded at timestamp t remains visible while the current timestamp satisfies current - window_duration < t. As time advances, older events automatically fall outside the window and should no longer be counted or returned.

For this problem, time advances by exactly 1 unit with each record operation. Query operations (count and recent) do not advance time.

Implement the function:

def sliding_event_log(window_duration: int, operations: List[str], arguments: List[List[object]]) -> List[object]

Parameters:

  • window_duration: A positive integer representing the time window size
  • operations: A list of operation names: "record", "count", or "recent"
  • arguments: A list of argument lists, one per operation
    • For "record": a single-element list containing the event data
    • For "count" and "recent": an empty list

Returns:

  • A list of results, one per operation:
    • record returns None
    • count returns an integer
    • recent returns a list of events in chronological order (oldest first)

Constraints:

  • 1 ≤ window_duration ≤ 10⁶
  • 1 ≤ number of operations ≤ 10⁴
  • Event data can be any hashable value
  • Time starts at 0 and increments by 1 with each record operation
  • Events are only visible while current_time - window_duration < event_time

Examples

Example 1

Input: sliding_event_log(3, ['record', 'count', 'record', 'recent', 'record', 'record', 'count', 'recent'], [['a'], [], ['b'], [], ['c'], ['d'], [], []])

Output: [None, 1, None, ['a', 'b'], None, None, 3, ['b', 'c', 'd']]

Hints

Hint 1

Consider a data structure that maintains events in time order and allows efficient removal from the front

Hint 2

Before each query, remove events that have fallen outside the time window based on the current timestamp

Hint 3

Track the current time separately and increment it only when recording new events