Skip to content

42. Merge Overlapping Sessions

Difficulty: Hard · Topic: Data wrangling

Each record is (user, start, end), a session in seconds, in no particular order. Write merge_sessions(sessions, gap=0): per user, merge sessions that overlap, touch, or are separated by at most gap seconds into one session.

Your code runs in CPython on our servers against 6 tests, including hidden ones.

Sample test

merge_sessions([('u1', 10, 20), ('u2', 0, 5), ('u1', 15, 30), ('u1', 40, 50)])

Expected: [('u1', 10, 30, 2), ('u1', 40, 50, 1), ('u2', 0, 5, 1)]

Hints

Hint 1Sort by (user, start); then each user's sessions come together and in time order.
Hint 2Keep a current merged session; the next one joins it when start - current_end <= gap and the user is the same.
Hint 3Extend with max(current_end, end), or nested sessions shrink the merged one.

Learn the concepts

More Python problems

All Python problems