Stateful Activity Window Aggregation Over an Event Stream
Data Structure DesignAuto-graded · 14 test casesLast updated
Tests whether a candidate can maintain per-user rolling time windows over a chronologically ordered stream and emit aggregated records incrementally without buffering the whole input.
You are building a pipeline stage that processes a chronologically ordered stream of chat activity records. Each record is a dictionary with the following fields:
event_name— always"send_message"timestamp— an ISO 8601 string in UTC, e.g."2024-03-15T09:22:00Z"user_id— a string identifying the senderchannel_id— a string identifying the destination channel
Records arrive in non-decreasing timestamp order. You may not assume the stream is finite, so your logic must never depend on reaching the end of the input. Process each record as it arrives and emit completed windows eagerly.
Activity Windows
For each user, define an activity window as a maximal sequence of that user's records where every consecutive pair is separated by 30 minutes or less. Formally:
- If the gap between a user's new record and their most recent previous record is strictly greater than 30 minutes, the previous window is closed and a new one begins.
- A gap of exactly 30 minutes keeps the new record in the same window.
A window is finalized — and must be emitted — the moment a later record from the same user proves the window is closed (i.e., the gap exceeds 30 minutes). Windows that are still open when the input ends are not emitted.
Output Format
Return a list of window records in the order they are finalized. Each record must be a dictionary with exactly these keys:
| Key | Type | Description |
|---|---|---|
user_id | str | The user this window belongs to |
session_start_ts | str | Timestamp string of the window's first record |
session_end_ts | str | Timestamp string of the window's last record |
messages_sent | int | Total number of records in the window |
top_channel_id | str | Channel with the highest record count in the window |
top_channel_messages_sent | int | Record count for top_channel_id |
Tie-breaking rule: when two or more channels share the highest count, pick the one whose channel_id string is lexicographically smallest. String comparison applies, so "10" sorts before "9".
Constraints
1 ≤ len(events) ≤ 10^6- All timestamps are valid ISO 8601 UTC strings ending in
Z user_idandchannel_idare non-empty strings- Records are guaranteed to be in non-decreasing timestamp order
- There are no missing or malformed fields
- A user may appear many times or only once
- Multiple users may be active concurrently; their windows are fully independent
Examples
Example 1
Input: sessionize_events([{'event_name': 'send_message', 'timestamp': '2016-11-08T14:09:57Z', 'user_id': '1', 'channel_id': '1'}, {'event_name': 'send_message', 'timestamp': '2016-11-08T14:10:01Z', 'user_id': '1', 'channel_id': '1'}, {'event_name': 'send_message', 'timestamp': '2016-11-08T14:10:07Z', 'user_id': '2', 'channel_id': '1'}, {'event_name': 'send_message', 'timestamp': '2016-11-08T14:40:08Z', 'user_id': '1', 'channel_id': '3'}])
Output: [{'user_id': '1', 'session_start_ts': '2016-11-08T14:09:57Z', 'session_end_ts': '2016-11-08T14:10:01Z', 'messages_sent': 2, 'top_channel_id': '1', 'top_channel_messages_sent': 2}]
Example 2
Input: sessionize_events([{'event_name': 'send_message', 'timestamp': '2024-01-01T00:00:00Z', 'user_id': 'u', 'channel_id': 'b'}, {'event_name': 'send_message', 'timestamp': '2024-01-01T00:30:00Z', 'user_id': 'u', 'channel_id': 'a'}, {'event_name': 'send_message', 'timestamp': '2024-01-01T01:00:01Z', 'user_id': 'u', 'channel_id': 'c'}])
Output: [{'user_id': 'u', 'session_start_ts': '2024-01-01T00:00:00Z', 'session_end_ts': '2024-01-01T00:30:00Z', 'messages_sent': 2, 'top_channel_id': 'a', 'top_channel_messages_sent': 1}]
Hints
Hint 1
For each user you only need to remember their current open window — not every past event. A dictionary keyed by user_id is the right structure.
Hint 2
You can decide whether to close a window the moment the *next* event from that user arrives. At that point, and only at that point, do you have enough information to know the previous window is final.
Hint 3
To pick the top channel under the tie-breaking rule, sort (or use min) with a key that ranks by descending count first and ascending channel string second: (-count, channel_id).
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is that you never need to see the full stream. For each user you only need to remember one thing: their currently open window. Store that in a dictionary keyed by user_id.
When a new record arrives for a user:
- Check whether their open window exists and whether the gap to the new record's timestamp is strictly greater than 30 minutes.
- If yes, the open window is provably final — no future record can belong to it because timestamps are non-decreasing. Emit it and discard its state.
- If no open window exists (either first record ever, or just closed in step 2), create a fresh window starting at this record.
- Add the record to the window: increment
messages_sent, increment the channel counter, updateend_tsandlast_time.
After consuming all records, return whatever was emitted. Open windows are intentionally ignored — the stream is treated as potentially infinite, so an open window has not been finalized.
Why It Is Correct
Window boundaries: we split exactly when the gap is strictly greater than 30 minutes. A gap of exactly 30:00 satisfies gap <= threshold, so the record stays in the current window. This matches the problem definition precisely.
Finality: a window is closed only after observing a later record from the same user with a gap above the threshold. Because records are globally non-decreasing in time, no subsequent record can ever fall inside the already-closed window. Emitting at this point is both safe and as early as possible.
Aggregates: every record is counted exactly once in the window it belongs to. top_channel_id is resolved from complete counts at close time.
Tie-breaking: min(channels, key=lambda ch: (-count[ch], ch)) sorts by descending count first, then ascending channel string. Among equal-count channels the one with the lexicographically smallest string wins — consistent with string, not numeric, ordering.
Timestamps: the original strings are preserved verbatim for session_start_ts and session_end_ts. Parsed datetime objects are used only for arithmetic and discarded.
Complexity
- Time: O(n). Each record costs O(1) for the dict lookup, counter update, and comparison. Closing a window costs O(c) where c is the number of distinct channels in that window; summed across all windows this is at most O(n).
- Space: O(U + C) where U is the number of users with open windows and C is the total number of distinct channels across those windows. Closed windows are discarded immediately.
Edge Cases
- Gap of exactly 30 minutes: stays in the same window (strict
>check). - Gap of 30 minutes and 1 second: old window is emitted, new one starts.
- User with only one record, or whose last window never closes: never emitted.
- Interleaved users: windows are fully independent; one user's records never affect another's.
- Channel ties: lexicographically smallest
channel_idstring wins;"10"beats"9". - Empty input: returns
[].
Reference Solution
from datetime import datetime, timedelta
from typing import Dict, List
def sessionize_events(events: List[Dict[str, str]]) -> List[Dict[str, object]]:
active = {} # user_id -> open window state
emitted = [] # finalized window records, in closing order
threshold = timedelta(minutes=30)
def close_window(user_id, window):
# Pick top channel: highest count wins; ties go to lex-smallest id.
top_channel = min(
window['channels'],
key=lambda ch: (-window['channels'][ch], ch)
)
emitted.append({
'user_id': user_id,
'session_start_ts': window['start_ts'],
'session_end_ts': window['end_ts'],
'messages_sent': window['messages_sent'],
'top_channel_id': top_channel,
'top_channel_messages_sent': window['channels'][top_channel],
})
for event in events:
user_id = event['user_id']
# datetime.fromisoformat on Python < 3.11 does not accept the 'Z' suffix.
timestamp = datetime.fromisoformat(event['timestamp'].replace('Z', '+00:00'))
window = active.get(user_id)
# A gap strictly greater than 30 minutes finalizes the open window.
if window is not None and timestamp - window['last_time'] > threshold:
close_window(user_id, window)
window = None
if window is None:
window = {
'start_ts': event['timestamp'],
'end_ts': event['timestamp'],
'last_time': timestamp,
'messages_sent': 0,
'channels': {},
}
active[user_id] = window
channel = event['channel_id']
window['channels'][channel] = window['channels'].get(channel, 0) + 1
window['messages_sent'] += 1
window['end_ts'] = event['timestamp']
window['last_time'] = timestamp
# No end-of-input flush: the stream may be infinite,
# so still-open windows have not been finalized.
return emitted