KatInterview

Split Overlapping Support Windows by Who Is Covering

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

Last 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. start and end are integers, person is a string.

Output

A list of (start, end, people) tuples, where each tuple stands for the half-open range [start, end).

Rules

  • start < end in every output tuple.
  • people is 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^4
  • 0 <= start < end <= 10^9
  • 1 <= 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.