A product analytics team at an online learning site wants to turn raw clickstream events into sessions.
Write sessionize(events, gapSeconds). Each event is (userId, timestampSeconds); the list is not sorted and may mix users. For each user, events belong to the same session while the time since that user's previous event is at most gapSeconds; a longer gap starts a new session. Return every session as (userId, startTimestamp, endTimestamp, eventCount), sorted by userId, then by startTimestamp.
Example (gapSeconds = 1800)
- Events:
("u1", 0), ("u1", 600), ("u2", 100), ("u1", 3000), ("u1", 3100), ("u2", 2000)
- Output:
("u1", 0, 600, 2), ("u1", 3000, 3100, 2), ("u2", 100, 100, 1), ("u2", 2000, 2000, 1)
A gap of exactly gapSeconds stays in the same session. A user with a single event has one session of zero length.
Constraints: up to 1,000,000 events and 100,000 users; timestamps are non-negative integers. Use any language.
Before coding, say how you will group and order the events and what the time and memory cost is. Then discuss how the approach would change if events arrived as a live stream, slightly out of order.