Sessionize Clickstream Events with a 30-Minute Inactivity Gap
SQL & DataAuto-graded · 14 test casesLast updated
Deduplicate retried events, split each user's activity into sessions on gaps over 30 minutes, and summarize each session with its start, end and distinct page count.
Sessionize Clickstream Events
A shopping site logs every page view as a record. Because of network retries, the same event can be logged more than once. You are given these records as a list of dictionaries and must turn them into per-session summaries.
Each record has these string fields:
event_id: identifier of the event. Records sharing anevent_idare retries of the same event.user_id: the user who viewed the page.page_url: the page that was viewed.timestamp: when the view happened, as an ISO-8601 style string such as"2023-10-01 10:00:00". All times are UTC. A trailingZmay appear.
Task
Implement a function that returns one summary row per session.
- Deduplicate. For each
event_id, keep only the first record in the input order and discard the later ones. - Order each user's events. Within a user, sort the remaining events by parsed time, then by
event_id(plain string comparison) to break ties. - Split into sessions. Walking a user's sorted events, a new session starts at the user's first event. It also starts at any event whose time is strictly more than 30 minutes (1800 seconds) after the immediately preceding event of that user. A gap of exactly 30 minutes stays in the same session. Gaps are measured between consecutive events, so a session may last longer than 30 minutes overall.
- Summarize. For every session, produce a dictionary with:
user_id: the user.session_id: the session's number for that user, starting at 1 and increasing in time order.session_start_time: thetimestampstring of the session's first event, exactly as given in the input.session_end_time: thetimestampstring of the session's last event, exactly as given in the input.page_count: the number of distinctpage_urlvalues in the session.
Output order
Return the list sorted by user_id in ascending string order. Within each user, sessions appear in ascending session_id order. If the input is empty, return an empty list.
Constraints
- 0 ≤ number of records ≤ 10^5.
- Every record contains all four fields, and every
timestampis a valid string. Within one input, all timestamps use the same format. - Times are in UTC, so no time-zone conversion is needed.
- Different users' events never affect each other's sessions.
- Repeated visits to the same page inside a session count once toward
page_count. - Duplicates are removed before any gap is computed.
Examples
Example 1
Input: build_session_report([{'event_id': '1', 'user_id': 'A', 'page_url': '/home', 'timestamp': '2023-10-01 10:00:00'}, {'event_id': '2', 'user_id': 'A', 'page_url': '/products', 'timestamp': '2023-10-01 10:15:00'}, {'event_id': '3', 'user_id': 'A', 'page_url': '/home', 'timestamp': '2023-10-01 10:50:00'}])
Output: [{'user_id': 'A', 'session_id': 1, 'session_start_time': '2023-10-01 10:00:00', 'session_end_time': '2023-10-01 10:15:00', 'page_count': 2}, {'user_id': 'A', 'session_id': 2, 'session_start_time': '2023-10-01 10:50:00', 'session_end_time': '2023-10-01 10:50:00', 'page_count': 1}]
Hints
Hint 1
Handle duplicates first: a dictionary keyed by event_id that keeps only the first record seen is enough.
Hint 2
Group the surviving events by user, sort each group by (parsed time, event_id), and compare each event only with the one directly before it. Parse the strings to datetimes so you can compare in seconds.
Hint 3
Open a new session when there is no previous event or the gap is strictly greater than 1800 seconds. Otherwise extend the current session by updating its end and adding the page to a set. Output the original timestamp strings.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is the classic "gaps and islands" sessionization pattern, done in three passes.
- Deduplicate. Scan the records and keep the first one seen for each
event_id, using a dictionary. Doing this first means retried events cannot affect gaps or page counts. - Group and order. Parse each timestamp into a
datetime, group events byuser_id, and sort each group by(parsed time, event_id). Theevent_idtie-break makes the order deterministic when two events share a timestamp. - Sweep to build sessions. Go through a user's sorted events and compare each one with the one just before it. If there is no previous event, or the gap is strictly greater than 1800 seconds, start a new session. Otherwise extend the current one by updating its end time and adding the page URL to a set. The size of that set is the distinct
page_count.
Finally, emit one dictionary per session, numbering sessions from 1 per user. Users are visited in sorted order, so the output order is user_id then session_id.
Why it is correct
- Only consecutive events are compared, which matches the rule that a session breaks only when two neighboring page views are far apart. A session can therefore span hours as long as no single gap exceeds 30 minutes.
- The comparison is strict (
>), so a gap of exactly 30 minutes stays in the same session. - The first event of each user always opens session 1.
- Because events are sorted, the last event processed in a session is the latest one, so it supplies the end time. The original timestamp strings are kept for output exactly as given.
- Deduplication happens before sorting, so duplicate retries never create phantom events.
Complexity
- Time: O(n log n), dominated by sorting each user's events. Deduplication, grouping and the sweep are linear.
- Space: O(n) for the deduplicated events, the groups and the output.
Reference solution
from datetime import datetime
from typing import Dict, List
def build_session_report(events: List[Dict[str, str]]) -> List[Dict[str, object]]:
# Step 1: keep the first record seen for every event_id.
unique = {}
for row in events:
if row["event_id"] not in unique:
unique[row["event_id"]] = row
# Step 2: group by user, parsing timestamps for comparison.
per_user = {}
for row in unique.values():
raw = row["timestamp"]
parsed = datetime.fromisoformat(raw.replace("Z", "+00:00"))
per_user.setdefault(row["user_id"], []).append(
(parsed, row["event_id"], raw, row["page_url"])
)
report = []
for user_id in sorted(per_user):
ordered = sorted(per_user[user_id], key=lambda e: (e[0], e[1]))
sessions = []
for parsed, _eid, raw, page in ordered:
if not sessions or (parsed - sessions[-1]["last"]).total_seconds() > 1800:
sessions.append({
"start": raw,
"end": raw,
"last": parsed,
"pages": set(),
})
current = sessions[-1]
current["end"] = raw
current["last"] = parsed
current["pages"].add(page)
for number, s in enumerate(sessions, start=1):
report.append({
"user_id": user_id,
"session_id": number,
"session_start_time": s["start"],
"session_end_time": s["end"],
"page_count": len(s["pages"]),
})
return report