You are given a list of user actions. Each action is [user_id, timestamp, action_name], where timestamp is measured in minutes. Group the actions into sessions.
A session is a run of consecutive actions by the same user in which the gap between any two consecutive actions (by timestamp) is strictly less than 30 minutes. When 30 or more minutes pass after a user's last action, that user's session ends, and the user's next action starts a new session.
Return all sessions across all users. Each session is a list of its actions sorted by timestamp, and the sessions are sorted by the timestamp of their first action.
Function Signature
def sessionize(actions: list[list]) -> list[list[list]]:
Rules
-
Each action is a list
[user_id, timestamp, action_name]
with
user_id: str
,
timestamp: int
(minutes) and
action_name: str
. The sessions contain the action lists themselves, with the same three values.
-
A gap of exactly 30 ends a session. A gap of 0 (two actions by the same user at the same timestamp) keeps both actions in the same session.
-
Actions with equal timestamps keep their relative order from the input.
-
Two sessions that start at the same timestamp belong to different users. The session whose first action appears earlier in the input comes first.
Constraints
-
1 <= len(actions) <= 10^5
-
user_id
and
action_name
are non-empty strings
-
0 <= timestamp <= 10^6
-
The actions are not necessarily sorted by timestamp
Examples
Input: actions = [["alice",0,"click"],["alice",10,"scroll"],["alice",25,"click"],["alice",60,"scroll"],["alice",70,"click"]]
Output: [[["alice",0,"click"],["alice",10,"scroll"],["alice",25,"click"]],[["alice",60,"scroll"],["alice",70,"click"]]]
The gaps 10 and 15 are both under 30, so the actions at 0, 10 and 25 form one session. The gap from 25 to 60 is 35, so the action at 60 starts a second session, and the action at 70 joins it with a gap of 10.
Input: actions = [["alice",0,"click"],["bob",5,"scroll"],["alice",20,"scroll"],["bob",40,"click"],["alice",55,"click"]]
Output: [[["alice",0,"click"],["alice",20,"scroll"]],[["bob",5,"scroll"]],[["bob",40,"click"]],[["alice",55,"click"]]]
Alice has one session starting at 0 (the action at 20 joins it) and another at 55 (gap 35). Bob's two actions are 35 apart, so each is its own session. Ordering the four sessions by start time gives 0, 5, 40, 55.
Input: actions = [["bob",30,"view"],["alice",0,"click"],["alice",30,"view"],["bob",30,"click"]]
Output: [[["alice",0,"click"]],[["bob",30,"view"],["bob",30,"click"]],[["alice",30,"view"]]]
Alice's gap from 0 to 30 is exactly 30, which ends her first session. Bob's two actions share a timestamp, so they stay together in input order. Bob's session and Alice's second session both start at 30, and Bob's first action comes earlier in the input, so his session is listed first.