call(back)
Algorithms & Data StructuresmediumSign in to star problems

Sessionize Events by Entity

events is an unordered list of [entity, timestamp] pairs. For each entity, group its events into sessions: consecutive events (in time order) that are at most gap apart belong to the same session. Return { entity: [[start, end, count], ...] } with each entity's sessions in time order.

sessionize([["u1", 1], ["u1", 5], ["u1", 30], ["u2", 2]], 10)
  ->  { "u1": [[1, 5, 2], [30, 30, 1]], "u2": [[2, 2, 1]] }

The gap is inclusive: events exactly gap apart share a session.

Hints

Hint 1

Sort by (entity, timestamp), then sweep: open a session on an entity's first event, extend it while the next timestamp is within gap of the session's current end, otherwise close it and open a new one.

Hint 2

The only state per entity is its open session — the last element of its list.

Asked at