Group Activity Logs into Time-Based Sessions
Arrays & HashingAuto-graded · 14 test casesLast updated
Tests time-series grouping, datetime arithmetic, gap-based segmentation, and aggregation with distinct counts.
You are given a list of activity log records. Each record is a dictionary with three fields:
user_id: a string identifying the userlog_datetime: a timestamp string in format"YYYY-MM-DD HH:MM:SS"topic: a string representing the activity category
Your task is to group these logs into sessions for each user, where a session is a sequence of consecutive events with no gap exceeding 30 minutes between adjacent events.
Session Rules
- Sort all records by user ID, then by timestamp.
- For each user, partition their events into sessions:
- A new session begins when the time gap from the previous event is strictly greater than 30 minutes, or when the user changes.
- Events exactly 30 minutes apart remain in the same session.
- For each session, compute:
user_id: the user identifiersession_start: the timestamp of the first event in the session (as a string)session_end:- If the session contains two or more events, use the timestamp of the last event
- If the session contains exactly one event, set
session_end = session_start + 30 minutes
count_topic: the number of distinct topics appearing in the sessioncount_time: the total number of events (records) in the session
Return a list of dictionaries, one per session, in the order sessions are encountered after sorting.
Example
Input:
[
{"user_id": "001", "log_datetime": "2025-03-01 00:01:00", "topic": "pricing"},
{"user_id": "001", "log_datetime": "2025-03-01 00:02:00", "topic": "hotel"},
{"user_id": "001", "log_datetime": "2025-03-01 00:03:00", "topic": "pricing"},
{"user_id": "001", "log_datetime": "2025-03-01 01:30:00", "topic": "restaurant"},
{"user_id": "001", "log_datetime": "2025-03-01 02:30:00", "topic": "restaurant"}
]
Output:
[
{"user_id": "001", "session_start": "2025-03-01 00:01:00", "session_end": "2025-03-01 00:03:00", "count_topic": 2, "count_time": 3},
{"user_id": "001", "session_start": "2025-03-01 01:30:00", "session_end": "2025-03-01 02:00:00", "count_topic": 1, "count_time": 1},
{"user_id": "001", "session_start": "2025-03-01 02:30:00", "session_end": "2025-03-01 03:00:00", "count_topic": 1, "count_time": 1}
]
Explanation:
- Events at 00:01, 00:02, and 00:03 form one session (gaps of 1 minute each). Two distinct topics: "pricing" and "hotel".
- Event at 01:30 starts a new session (87-minute gap from 00:03). Single event, so end time is 01:30 + 30 minutes = 02:00.
- Event at 02:30 starts a new session (60-minute gap from 01:30). Single event, so end time is 03:00.
Constraints
- 0 ≤ number of records ≤ 100,000
- All timestamps are valid and in format
"YYYY-MM-DD HH:MM:SS" user_idandtopicare non-empty strings- Records may arrive in any order; you must sort them
- Multiple users may be present in the input
- A user may have multiple sessions
Examples
Example 1
Input: group_activity_sessions([{'user_id': '001', 'log_datetime': '2025-03-01 00:01:00', 'topic': 'pricing'}, {'user_id': '001', 'log_datetime': '2025-03-01 00:02:00', 'topic': 'hotel'}, {'user_id': '001', 'log_datetime': '2025-03-01 00:03:00', 'topic': 'pricing'}, {'user_id': '001', 'log_datetime': '2025-03-01 01:30:00', 'topic': 'restaurant'}, {'user_id': '001', 'log_datetime': '2025-03-01 02:30:00', 'topic': 'restaurant'}])
Output: [{'user_id': '001', 'session_start': '2025-03-01 00:01:00', 'session_end': '2025-03-01 00:03:00', 'count_topic': 2, 'count_time': 3}, {'user_id': '001', 'session_start': '2025-03-01 01:30:00', 'session_end': '2025-03-01 02:00:00', 'count_topic': 1, 'count_time': 1}, {'user_id': '001', 'session_start': '2025-03-01 02:30:00', 'session_end': '2025-03-01 03:00:00', 'count_topic': 1, 'count_time': 1}]
Hints
Hint 1
Sort all records by (user_id, log_datetime) first, then process them in a single linear pass.
Hint 2
Track the previous event's timestamp. When the gap exceeds 30 minutes or the user changes, close the current session and start a new one.
Hint 3
Don't forget to finalize the last session after the loop ends—this is a common source of bugs.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires sessionization: partitioning time-ordered events into groups where consecutive events are close together in time.
The solution follows a two-phase pattern:
-
Sort all records by
(user_id, log_datetime). This groups each user's events together and orders them chronologically. -
Single-pass sweep through the sorted records. Maintain a buffer of events belonging to the current session. Close the session and start a new one whenever:
- The user ID changes from the previous record, or
- The time gap from the previous event is strictly greater than 30 minutes
When closing a session, compute its aggregates:
session_start: timestamp of the first eventsession_end: timestamp of the last event if 2+ events exist; otherwisestart + 30 minutescount_topic: size of the set of distinct topicscount_time: number of events in the session
Why This Works
User boundaries: After sorting, all events for a given user are adjacent. Comparing the current user ID with the previous one detects user boundaries correctly.
Gap rule: A session is a maximal chain where each consecutive gap is ≤ 30 minutes. We only need to check the gap between adjacent events (not from session start), because the rule defines the split based on the gap from the previous event. A session can span hours as long as events keep arriving within 30 minutes of each other.
Strictness: The condition is gap > 30 minutes. Events exactly 30 minutes apart stay in the same session.
Single-event sessions: These have no natural end time, so we assign 30 minutes as the assumed duration. Multi-event sessions always use the actual last event timestamp, even if it's less than 30 minutes from the start.
Walking through the example:
00:01 → 00:02 → 00:03: gaps of 1 minute each → one session. Distinct topics: {pricing, hotel} = 2. Events: 3. End: 00:03.01:30: gap of 87 minutes from 00:03 → new session. One event → end = 01:30 + 30min = 02:00.02:30: gap of 60 minutes from 01:30 → new session. One event → end = 03:00.
Complexity
Time: O(n log n) for sorting + O(n) for the sweep. Each record is processed once and added to exactly one session.
Space: O(n) for the sorted list and output. The session buffer can grow to O(n) in the worst case (all events in one session).
Solution
from datetime import datetime, timedelta
from typing import Dict, List
def group_activity_sessions(rows: List[Dict[str, str]]) -> List[Dict[str, object]]:
events = sorted(rows, key=lambda row: (row["user_id"], row["log_datetime"]))
result = []
current_user = None
session = []
def finish_session():
if not session:
return
start = datetime.fromisoformat(session[0]["log_datetime"])
end = datetime.fromisoformat(session[-1]["log_datetime"])
if len(session) == 1:
end = start + timedelta(minutes=30)
result.append({
"user_id": session[0]["user_id"],
"session_start": start.strftime("%Y-%m-%d %H:%M:%S"),
"session_end": end.strftime("%Y-%m-%d %H:%M:%S"),
"count_topic": len({row["topic"] for row in session}),
"count_time": len(session),
})
previous_time = None
for row in events:
timestamp = datetime.fromisoformat(row["log_datetime"])
if current_user != row["user_id"] or (previous_time is not None and timestamp - previous_time > timedelta(minutes=30)):
finish_session()
session = []
current_user = row["user_id"]
session.append(row)
previous_time = timestamp
finish_session()
return result