KatInterview

Consolidate Overlapping Time Ranges by Group

Greedy & IntervalsAuto-graded · 16 test cases
EasyAuto-gradedGreedy & Intervalsintervalsgroupingsorting

Last 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 group
  • start_time: a string timestamp marking the beginning of the interval
  • end_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_id is 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.