KatInterview

Staffing Timeline from Overlapping Work Shifts

Greedy & IntervalsModel answer
MediumModel answerGreedy & Intervalssweep-lineintervalshash-map

Last updated

Turn a list of overlapping employee shifts into contiguous time segments, each listing who is on duty, with empty segments marking gaps in coverage.

Staffing Timeline

A scheduling tool stores shifts as records with an employee id, a name, and integer start and end times. Several employees can be on duty at once. Write a function that converts these shifts into a staffing timeline: an ordered list of non-overlapping segments, where each segment gives the exact set of people on duty during that stretch of time.

def get_coverage_timeline(shifts: List[Dict]) -> List[Dict]

Input

shifts is a list of dictionaries such as {'id': 1, 'name': 'Alice', 'start': 10, 'end': 20}.

Output

A list of dictionaries, each with:

  • start and end: the bounds of the segment,
  • employees: a list of {'id', 'name'} entries for everyone on duty in that segment.

If nobody is on duty for a stretch that lies between the earliest start and the latest end, emit a segment for it with an empty employees list (a break).

Example

Input:

[
  {'id': 1, 'name': 'Alice', 'start': 0, 'end': 10},
  {'id': 2, 'name': 'Bob',   'start': 5, 'end': 15}
]

Output:

[
  {'start': 0,  'end': 5,  'employees': [{'id': 1, 'name': 'Alice'}]},
  {'start': 5,  'end': 10, 'employees': [{'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bob'}]},
  {'start': 10, 'end': 15, 'employees': [{'id': 2, 'name': 'Bob'}]}
]

Constraints

  • 0 <= start < end, all times are non-negative integers.
  • n, the number of shifts, is at most 10,000.

Cases to handle

  • Back-to-back shifts (one ends at 10, another starts at 10).
  • A shift fully inside another shift.
  • An empty input list.

What to cover in your answer

State your assumptions (interval semantics, ordering, how duplicates are treated), describe the algorithm, justify its correctness, give time and space complexity (mind the output size), and provide code.

Hints

Hint 1

The set of people on duty can only change at a shift's start or end time. What happens if you sort all of those distinct times and look at each gap between neighbours?

Hint 2

Treat each shift as two events, +1 at its start and -1 at its end. Process all events sharing the same timestamp before you emit the next segment, so touching shifts need no special handling.

Hint 3

The same employee id may hold overlapping shifts. A plain set would remove them too early, so think about what per-id bookkeeping keeps them present until their last shift ends.