Premium problem159. Split Events into Sessions

Hard Locked

events has columns user_id and event_time (datetime).

A new session starts whenever the gap from a user's previous event is strictly greater than gap_minutes. Number each user's sessions from 1 independently, so every user's first event is session 1.

Return the original columns plus session_id, sorted by user_id then event_time, with the index renumbered from 0.

The running session number is a cumulative sum of "did a new session start here", computed within each user.

Input

events =
   user_id          event_time
0        1 2022-01-01 10:00:00
1        1 2022-01-01 10:20:00
2        1 2022-01-01 11:30:00
3        1 2022-01-01 11:45:00
4        2 2022-01-01 08:00:00
5        2 2022-01-01 08:31:00
gap_minutes = 30

Output

   user_id          event_time  session_id
0        1 2022-01-01 10:00:00           1
1        1 2022-01-01 10:20:00           1
2        1 2022-01-01 11:30:00           2
3        1 2022-01-01 11:45:00           2
4        2 2022-01-01 08:00:00           1
5        2 2022-01-01 08:31:00           2

Premium problem

This one's part of Premium. Unlock the full Pandas track plus every other premium problem on the site.

Implement solve(...)