← Problems53. Sessionize a clickstream in PythonMediumPython
00:00 / 25:00

Sessionize a clickstream in Python

Medium100% solve itAsked at Amazon

A product analytics pipeline receives a raw clickstream and must group each user's events into sessions. A session ends when a user is inactive for 30 minutes or more; the next event starts a new session.

The feed arrives unsorted, and a retry can deliver the same event_id twice.

Input schema

events — a list of dicts:

columntypenotes
event_idintunique per event; duplicates may arrive
user_idstr
tsstrYYYY-MM-DD HH:MM:SS, arrives unsorted

Return

One row per session, as a list of dicts with keys in this order:

user_id, session_index, started_at, ended_at, event_count

session_index starts at 1 per user, ordered by time.

Constraints

  • A gap of exactly 30 minutes starts a new session.
  • Deduplicate on event_id before sessionizing; a duplicate must not inflate event_count.
  • Output ordered by user_id, then session_index.
  • Up to 200,000 events; the reference runs in well under a second.

Example 1two sessions, one gap

Input · events
tsuser_idevent_id
2026-03-01 09:00:00u11
2026-03-01 09:20:00u12
2026-03-01 10:05:00u13
Output
user_idsession_indexstarted_atended_atevent_count
u112026-03-01 09:00:002026-03-01 09:20:002
u122026-03-01 10:05:002026-03-01 10:05:001

Example 2two users, unsorted feed

Input · events
tsuser_idevent_id
2026-03-01 11:00:00u25
2026-03-01 09:10:00u11
2026-03-01 11:15:00u26
2026-03-01 09:00:00u12
Output
user_idsession_indexstarted_atended_atevent_count
u112026-03-01 09:00:002026-03-01 09:10:002
u212026-03-01 11:00:002026-03-01 11:15:002

Topics

sessionizationwindowing

Similar problems

Community-reported interview topic. Not an official company question and no affiliation is implied.

solution.py
Loading editor…
Draft not saved yet · Spaces 4 · UTF-8⌘↵ run ⌘⇧↵ submit
Nothing run yet

Run against the public tests, or submit to score against all of them.