Sessionize user events

Write codeHard35 minDatabricks and Snowflake style

Your task

Sessionize a stream of user events. Input is a list of (user, ts) tuples already sorted by ts ascending overall, plus an integer 'gap'. For each user independently, consecutive events belong to the same session if the difference between an event's ts and the previous event's ts (for that user) is <= gap; a larger difference starts a new session. Return a list of (user, session_count) tuples for every user that appears, sorted by user ascending. The input may be empty. A user with a single event has 1 session.

Examples

count_sessions(events: list[tuple], gap: int) -> list[tuple]
Example 1
Inputcount_sessions([["a", 1], ["a", 3], ["a", 10], ["b", 2]], 5)
Output[["a", 2], ["b", 1]]