Staffing Timeline from Overlapping Work Shifts
Greedy & IntervalsModel answerLast 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:
startandend: 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions to confirm first
- Half-open intervals
[start, end). A shift ending at 10 and another starting at 10 do not overlap. They yield adjacent segments that meet at 10 with no break between them. - Breaks are segments with
employees: [], but only between the earliest start and the latest end. Nothing is emitted before or after that range. - Ordering: employees inside a segment are sorted by
id, which makes output deterministic and matches the example. - Identity is the
id. If one employee holds overlapping or touching shifts, they appear once per segment. - Empty input returns
[].
Approach: sweep line over event times
The on-duty set changes only at shift boundaries. So:
- Build a map from time to the list of events at that time:
+1for a start,-1for an end, each carrying the id and name. - Sort the distinct timestamps.
- Walk them in order, keeping
active_count, a map from id to the number of currently open shifts for that id. - At each timestamp
t(except the first), first emit the segment[prev, t)using the current active set, which reflects the state before changes att. Then apply all events att.
Because events at the same time are applied together and timestamps are distinct, no zero-length segment is produced, and touching shifts are handled naturally.
Why a reference count and not a set
Suppose employee 1 works [0,10) and [5,15). A set would delete them at time 10, although the second shift is still open. With a count, the value is 2 during [5,10), drops to 1 at 10, and reaches 0 only at 15. The employee is removed only at 0.
Correctness sketch
Invariant: on reaching timestamp t[i], active_count contains exactly the ids that have at least one shift with start <= t[i-1] < end.
- Initially the structure is empty, which is correct before the first timestamp.
- After applying all events at
t[i-1], every shift that has started and not ended is accounted for. - No event occurs strictly between consecutive timestamps, so that set is the true staffing for the entire span
[t[i-1], t[i]).
Every moment in [min start, max end) lies in exactly one such span, so the segments are contiguous, non-overlapping and complete.
Complexity
- Sorting 2n events (or at most 2n distinct times): O(n log n).
- Applying events: O(1) each.
- Emitting segments: each segment lists its active employees, sorted. If
Sis the total size of the output, this costs O(S log n). In the worst caseSis Θ(n²), for example n nested shifts producing about 2n segments with up to n people each. No algorithm can beat O(S) because that is the answer's size. - Total time: O(n log n + S log n). Space: O(n) working memory plus O(S) output.
The per-segment sort can be avoided with a sorted container keyed by id, but it is rarely necessary.
Code
from collections import defaultdict
from typing import Dict, List
def get_coverage_timeline(shifts: List[Dict]) -> List[Dict]:
if not shifts:
return []
events = defaultdict(list) # time -> [(delta, id, name)]
for s in shifts:
events[s['start']].append((1, s['id'], s['name']))
events[s['end']].append((-1, s['id'], s['name']))
times = sorted(events)
active_count: Dict = {} # id -> open shifts
names: Dict = {} # id -> name
timeline: List[Dict] = []
for i, t in enumerate(times):
if i > 0:
timeline.append({
'start': times[i - 1],
'end': t,
'employees': [{'id': e, 'name': names[e]}
for e in sorted(active_count)],
})
for delta, eid, name in events[t]:
if delta == 1:
active_count[eid] = active_count.get(eid, 0) + 1
names[eid] = name
else:
active_count[eid] -= 1
if active_count[eid] == 0:
del active_count[eid]
del names[eid]
return timeline
Trace on the example: the timestamps are [0, 5, 10, 15]. At 5 we emit [0,5) with Alice, then add Bob. At 10 we emit [5,10) with Alice and Bob, then remove Alice. At 15 we emit [10,15) with Bob.
Edge cases
| Case | Result |
|---|---|
| No shifts | [] |
| Touching shifts (end 10, start 10) | Two adjacent segments, no break |
| Nested shift | Three segments: outer, both, outer |
| Gap between shifts | Segment with employees: [] |
| Same id, overlapping shifts | Listed once, kept alive by the count |
| Many events at one timestamp | Applied together before the next emit |
Common mistakes
- Using a set instead of a count, which drops an employee too early when their own shifts overlap.
- Emitting a segment after applying the events at
trather than before, which shifts every segment by one step. - Handling touching shifts with special cases instead of grouping events by timestamp.
- Claiming O(n log n) overall while ignoring that the output itself can be quadratic.
- Emitting breaks before the first start or after the last end.
Follow-ups worth preparing
- Headcount only: keep a difference map (+1 at start, -1 at end) and a running prefix sum. This is O(n log n) time with O(n) output. If the time range T is small, an array gives O(n + T).
- Merge equal neighbours: before appending a segment, compare its employee list to the previous one and extend the previous
endif they match. This is useful when one person's shift ends exactly as another of theirs begins. - Streaming or huge inputs: if shifts arrive already sorted by start, use a min-heap of end times to avoid a full global sort of events.