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.
- Return a list of
(user, start, end, count)tuples, wherecountis how many input sessions were merged, sorted by user and then start. - A session nested inside another (
(1, 10)and(2, 3)) merges into the outer one; the merged end is the largest end, not the last one.
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 1
Sort by(user, start); then each user's sessions come together and in time order.Hint 2
Keep a current merged session; the next one joins it whenstart - current_end <= gap and the user is the same.Hint 3
Extend withmax(current_end, end), or nested sessions shrink the merged one.Learn the concepts
- Sorting with key functions · 5 min read. Tuple keys, mixed directions, stability and data with None in it.
- Sliding windows, sweeps and binary search · 5 min read. O(n) windows, sort-then-sweep for intervals, and bisect for as-of lookups.
More Python problems
- Parse Log Lines into Records · Easy
- Reformat Date Strings · Easy
- CSV Rows to Typed Records · Easy
- Flatten Nested JSON · Medium
- Keep the Latest Record per Key · Medium
- Group and Aggregate without pandas · Medium
- Left Join Two Lists of Dicts · Medium
- Schema Validation with a Dead-Letter Queue · Hard