Consolidate Overlapping Time Ranges by Group
Greedy & IntervalsAuto-graded · 16 test casesLast updated
Tests interval merging within distinct groups, requiring grouping logic, sorting, and adjacent-interval handling.
You are given a list of records, where each record represents a time span for a particular group. Each record is a dictionary containing:
employee_id: an integer identifying the groupstart_time: a string timestamp marking the beginning of the intervalend_time: a string timestamp marking the end of the interval
Some intervals for the same employee_id may overlap or touch end-to-end. Your task is to combine all such intervals within each group into a minimal set of non-overlapping ranges.
Two intervals should be merged if they overlap or if one ends exactly where the other begins (the end_time of one equals the start_time of the other).
Write a function that takes the list of records and returns a new list where overlapping or adjacent intervals for each employee_id have been consolidated. The output must be sorted first by employee_id, then by start_time.
Constraints
1 ≤ len(rows) ≤ 100,000- Each interval satisfies
start_time ≤ end_time - Timestamps are ISO 8601 strings and can be compared lexicographically
employee_idis a positive integer
Examples
Example 1
Input: merge_employee_tasks([{'employee_id': 1, 'start_time': '2023-01-01T08:00:00', 'end_time': '2023-01-01T10:00:00'}, {'employee_id': 1, 'start_time': '2023-01-01T09:00:00', 'end_time': '2023-01-01T11:00:00'}, {'employee_id': 1, 'start_time': '2023-01-01T12:00:00', 'end_time': '2023-01-01T13:00:00'}, {'employee_id': 2, 'start_time': '2023-01-01T08:00:00', 'end_time': '2023-01-01T09:00:00'}])
Output: [{'employee_id': 1, 'start_time': '2023-01-01T08:00:00', 'end_time': '2023-01-01T11:00:00'}, {'employee_id': 1, 'start_time': '2023-01-01T12:00:00', 'end_time': '2023-01-01T13:00:00'}, {'employee_id': 2, 'start_time': '2023-01-01T08:00:00', 'end_time': '2023-01-01T09:00:00'}]
Hints
Hint 1
Sort the records by employee_id and start_time first; this lets you process intervals for each group in order.
Hint 2
Keep track of the current open interval. If the next interval overlaps or touches it, extend the open interval's end. Otherwise, finalize the current interval and start a new one.
Hint 3
Use <= when comparing times to merge adjacent intervals (end equals start). A strict < would leave touching intervals separate.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is the interval-merging problem applied separately to each group. The core insight is that once you sort by (employee_id, start_time), all intervals belonging to the same employee appear consecutively, and within each employee the intervals are ordered by when they begin. You can then scan through the sorted list once, maintaining the most recent "open" interval:
- Sort the input by
employee_id, thenstart_time, thenend_time. - Iterate through the sorted records. For each record:
- If the output is empty, or the current record belongs to a different employee, or its start time is after the open interval's end, finalize the open interval and start a new one.
- Otherwise, the current record overlaps or touches the open interval. Extend the open interval's end to the maximum of its current end and the new record's end.
- Return the consolidated list.
Using <= when comparing start versus the open end ensures that adjacent intervals (where one ends exactly when the next begins) are merged. Tracking the maximum end time, rather than always using the most recent interval's end, handles cases where a later interval is fully contained within an earlier merged block.
Why It Works
Within one employee's intervals, consider the open block [S, E] that already incorporates all earlier overlapping intervals. The next interval [s, e] has s ≥ S because of the sort. If s ≤ E, then [s, e] overlaps or touches [S, E], so we extend E to max(E, e). If s > E, no later interval (which starts even later) can connect back to [S, E], so that block is complete.
The sort also groups intervals by employee_id, preventing intervals from different employees from merging even if their times overlap.
Complexity
- Time: O(n log n) for sorting, then O(n) for the single-pass merge. For n ≤ 100,000 this is efficient.
- Space: O(n) for the sorted copy and the output list.
Solution Code
from typing import Dict, List
def merge_employee_tasks(rows: List[Dict]) -> List[Dict]:
ordered = sorted(
rows,
key=lambda row: (row["employee_id"], row["start_time"], row["end_time"])
)
merged = []
for row in ordered:
emp_id = row["employee_id"]
start = row["start_time"]
end = row["end_time"]
if (
merged
and merged[-1]["employee_id"] == emp_id
and start <= merged[-1]["end_time"]
):
if end > merged[-1]["end_time"]:
merged[-1]["end_time"] = end
else:
merged.append({
"employee_id": emp_id,
"start_time": start,
"end_time": end
})
return merged