Sliding Window Event Log with Time-Based Expiration
Data Structure DesignAuto-graded · 15 test casesLast 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 timestampcount: Return how many events are currently within the time windowrecent: 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 sizeoperations: 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
- For
Returns:
- A list of results, one per operation:
recordreturnsNonecountreturns an integerrecentreturns 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
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The key insight is to maintain events in chronological order using a queue-like structure, where we can efficiently add new events at the end and remove expired events from the front.
Data Structure Choice: Use a double-ended queue (deque) to store pairs of (timestamp, event_data). This supports O(1) append at the back and O(1) removal from the front.
Time Tracking: Maintain a counter for the current time, which starts at 0 and increments by 1 each time a record operation occurs. Query operations don't advance time.
Window Expiration:
Before processing any operation, clean up expired events. An event at timestamp t is expired if current_time - window_duration >= t (equivalently, t <= current_time - window_duration). Remove all such events from the front of the deque.
Operation Handling:
record: Increment time, append the new (timestamp, event) pair, then clean up expired entriescount: Clean up expired entries, then return the deque lengthrecent: Clean up expired entries, then extract and return just the event data (not timestamps) in order
Why This Works: Since time only advances forward and events are added with strictly increasing timestamps, the deque remains sorted by time. Expired events are always at the front, so we can remove them efficiently until we hit an event that's still valid.
Complexity:
- Time: O(n) total across all operations, where n is the number of events recorded. Each event is added once and removed once. Individual operations are amortized O(1).
- Space: O(w) where w is the maximum number of events within the window at any point, which is at most n.
from collections import deque
from typing import List
def sliding_event_log(window_duration, operations, arguments):
events = deque()
results = []
current_time = 0
def remove_expired():
while events and events[0][0] <= current_time - window_duration:
events.popleft()
for operation, args in zip(operations, arguments):
if operation == "record":
current_time += 1
events.append((current_time, args[0]))
remove_expired()
results.append(None)
elif operation == "count":
remove_expired()
results.append(len(events))
elif operation == "recent":
remove_expired()
results.append([event for _, event in events])
else:
raise ValueError("unknown operation")
return results