Split Overlapping Support Windows by Who Is Covering
Greedy & IntervalsModel answerLast updated
Break a set of possibly overlapping staffed time windows into disjoint half-open segments, each labeled with the sorted set of people covering it, dropping gaps and merging equal neighbors.
Coverage Timeline Builder
A support team keeps a record of who is covering the pager at any moment. Each record is a window (start, end, person), and windows may overlap, including several windows for the same person.
Produce a timeline that cuts the covered time into consecutive, non-overlapping pieces. Within one piece, the group of people covering must not change.
Implement:
def build_coverage(
windows: list[tuple[int, int, str]]
) -> list[tuple[int, int, list[str]]]:
pass
Input
windows: a list of(start, end, person)tuples.startandendare integers,personis a string.
Output
A list of (start, end, people) tuples, where each tuple stands for the half-open range [start, end).
Rules
start < endin every output tuple.peopleis sorted in ascending lexicographic order and has no repeated names.- Stretches where nobody is covering do not appear in the output.
- If two output pieces touch (the first ends exactly where the second begins) and have the identical list of people, they must be reported as one piece.
- The output is ordered by
start, ascending.
Examples
windows = [(1, 5, "Alice"), (3, 7, "Bob")]
# [(1, 3, ["Alice"]), (3, 5, ["Alice", "Bob"]), (5, 7, ["Bob"])]
windows = [(1, 4, "Alice"), (2, 4, "Bob"), (6, 8, "Alice")]
# [(1, 2, ["Alice"]), (2, 4, ["Alice", "Bob"]), (6, 8, ["Alice"])]
Nobody covers 4 to 6, so that range is left out.
Constraints
0 <= len(windows) <= 2 * 10^40 <= start < end <= 10^91 <= len(person) <= 30, alphanumeric characters only.
What to deliver
Describe your approach, justify its correctness, state time and space complexity, discuss the tricky cases, and give working code.
Hints
Hint 1
The set of people covering can only change at a time where some window starts or ends. What happens if you look only at those times?
Hint 2
Turn each window into a +1 event at its start and a -1 event at its end, group events by timestamp, and process every event at a timestamp before you emit anything for the range that follows.
Hint 3
A person can hold overlapping windows, so a plain set is not enough: removing them when one window ends may be wrong. Track a counter per person. Only merge with the previous piece if it ends exactly at the current time and has the same list.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach: sweep line over change points
The group of people covering can only change at a timestamp where some window begins or ends. Between two consecutive such timestamps the group is fixed. So:
- Convert each window
(s, e, p)into two events:(p, +1)atsand(p, -1)ate. - Bucket events by timestamp and sort the distinct timestamps
t_0 < t_1 < ... < t_m. - Walk through the timestamps. At
t_i, apply all events for that timestamp. The state then describes exactly[t_i, t_{i+1}). - If the state is empty, skip (gap). Otherwise build the sorted list of people. If the last emitted piece ends at
t_iand has the same list, extend it tot_{i+1}. Otherwise append a new piece.
Why a counter and not a set
A person can have nested or overlapping windows, for example (1, 5, "A") and (2, 3, "A"). With a set, the end event at time 3 removes A even though A still covers until 5. A per-person counter fixes this: a person is active while their count is above zero. Exact duplicate windows work too: the count is 2, but the name shows up once.
Correctness
- Constant inside a segment. No boundary lies strictly inside
[t_i, t_{i+1}), so each window either covers the whole range or none of it. After applying all events att_i, the people with positive counts are exactly those withs <= t_i < e. The half-open convention means an end att_iremoves and a start att_iadds, which is what we want. - Order within one timestamp is irrelevant, because we record the state only after all events at that time are applied. A person whose count briefly hits 0 and returns to 1 at the same timestamp ends up active, as they should.
- Counts never go negative. A
-1at timetbelongs to a window that started strictly earlier, so its+1has been applied in an earlier step. - Merging needs both contiguity (
prev_end == t_i) and equal lists. Two stretches with the same people separated by a gap stay separate, as with(6, 8, ["Alice"])in the second example. - Ordering. Timestamps are processed in increasing order, so output is sorted by
start. - The last timestamp never begins a piece: all windows have ended, so the state is empty.
Complexity
With n windows there are at most 2n distinct timestamps.
- Time:
O(n log n)to sort timestamps, plusO(k log k)per emitted piece to sort itsknames. Output size can be quadratic (for examplennested windows by different people give pieces of sizes up ton), so the real bound isO(n log n + sum of k log k). Any solution must write the output, so this is optimal up to the log factor. Forn = 2*10^4this is fine. - Space:
O(n)for events and counters, plus the output.
Code
from collections import defaultdict
def build_coverage(windows):
if not windows:
return []
events = defaultdict(list) # time -> [(person, delta)]
for s, e, p in windows:
events[s].append((p, 1))
events[e].append((p, -1))
times = sorted(events)
active = defaultdict(int) # person -> number of open windows
out = []
for i in range(len(times) - 1):
t, nxt = times[i], times[i + 1]
for p, d in events[t]:
active[p] += d
if active[p] == 0:
del active[p]
if not active:
continue # gap
people = sorted(active)
if out and out[-1][1] == t and out[-1][2] == people:
out[-1] = (out[-1][0], nxt, people)
else:
out.append((t, nxt, people))
return out
Edge cases to mention
- Empty input returns
[]. - Back-to-back windows for one person,
(1,3,"A"), (3,5,"A"), collapse into(1, 5, ["A"]). - Nested windows for one person,
(1,5,"A"), (2,3,"A"), give(1, 5, ["A"]). - A handoff
(1,3,"A"), (3,5,"B")produces two adjacent pieces with no gap, because the lists differ. - Timestamps up to
10^9: use only the event points, never a dense array.
Common mistakes
- Using a set instead of counters.
- Emitting a piece after each individual event instead of after all events at the same time, which creates zero-length or wrong pieces.
- Merging pieces that have equal lists but are separated by a gap.
- Forgetting to sort names, or comparing an unsorted list when merging.
- Mutating the previous tuple incorrectly (tuples are immutable, so replace it).
Follow-ups
- Adding or cancelling windows dynamically. Keep the per-timestamp deltas in an ordered map (balanced tree or
SortedDict). A change touches two keys. Only the range[s, e)needs re-sweeping, seeded with the state ats, plus a possible merge check at the two boundaries. - Who is covering at time
t? For a static schedule, store the output andbisecton starts: find the last piece withstart <= tand checkt < end. That isO(log n)plus the cost of returning the list. For a dynamic schedule, use an interval tree. - Weighted roles. Store
[count, total_weight]per person and merge only when both the list and the weights match.