---
title: Sessionise user events
url: https://gurkanozkan.ai/learn/coding/mle-sessionise-user-events-02/
markdown: https://gurkanozkan.ai/learn/coding/mle-sessionise-user-events-02.md
kind: coding
difficulty: Easy
topics:
  - Data manipulation
  - Sorting
  - Sessions
json: https://gurkanozkan.ai/api/learn/coding/mle-sessionise-user-events-02.json
robots: noindex
---

# Sessionise user events

Events are `(user_id, timestamp_seconds)` in arbitrary order. For each user, a new session starts when the gap between consecutive events (after sorting by time) is **strictly greater** than `gap`. Return `{user: number_of_sessions}`; users without events are absent.

## Signature

```python
def count_sessions(events: list[tuple[str, int]], gap: int) -> dict[str, int]: ...
```

## Examples

Each call and the value it should give.

```python
>>> count_sessions([('a',0),('a',10),('a',100)], 30) == {'a': 2}
True

>>> count_sessions([('a',100),('a',0),('a',10)], 30) == {'a': 2}
True
```

## Hints

1. Group events per user first — the input is not sorted.
2. Sort timestamps per user, then count gaps strictly greater than gap.
3. Duplicate timestamps produce a gap of 0 — that is not a new session.

## Reference solution

```python
from collections import defaultdict

def count_sessions(events, gap):
    by_user = defaultdict(list)
    for u, t in events:
        by_user[u].append(t)
    out = {}
    for u, ts in by_user.items():
        ts.sort()
        n = 1
        for a, b in zip(ts, ts[1:]):
            if b - a > gap:
                n += 1
        out[u] = n
    return out
```

## What a strong solution covers

- Groups by user, then sorts timestamps per user (O(n log n)).
- Uses the strict inequality as specified, and handles duplicate timestamps.
- Follow-up: streaming version with per-user last-seen state.

## Common mistakes

- assuming input is pre-sorted
- using `>=` instead of `>`.
---

*Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.*
