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

Sessionize a clickstream in Python

Medium·Acceptance ·Asked 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:

| column | type | notes | |---|---|---| | event_id | int | unique per event; duplicates may arrive | | user_id | str | | | ts | str | YYYY-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.

Example

events = [ {"event_id": 1, "user_id": "u1", "ts": "2026-03-01 09:00:00"}, {"event_id": 2, "user_id": "u1", "ts": "2026-03-01 09:20:00"}, {"event_id": 3, "user_id": "u1", "ts": "2026-03-01 10:05:00"}, ]

The gap between 09:20 and 10:05 is 45 minutes, so:

[ {"user_id": "u1", "session_index": 1, "started_at": "2026-03-01 09:00:00", "ended_at": "2026-03-01 09:20:00", "event_count": 2}, {"user_id": "u1", "session_index": 2, "started_at": "2026-03-01 10:05:00", "ended_at": "2026-03-01 10:05:00", "event_count": 1}, ]

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.

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.