Sorted, with repeats dropped, free days become runs of days in a row
An on-call engineer is free on days {3, 4, 5, 8, 9, 12}. Free time often comes like this, as a set of days rather than as intervals. The question you'll keep asking is which stretches of days in a row that makes.
Predict
Free days {3, 4, 5, 8, 9, 12}. How many runs of days in a row do they make?
The free days, colored by run
free
3458912
The runs are (3, 5), (8, 9) and (12, 12). Days 6, 7, 10 and 11 are busy.
The answer is a list of closed intervals called runs: (3, 5), (8, 9) and (12, 12). Sort the days, then walk them once. A day that is one after the end of the last run extends it. Any other day starts a new run.
Two details matter. The days can come in any order, so sort them. And they can repeat. Here is the walk on [12, 9, 3, 5, 4, 8, 4], once with the repeats kept and once with them dropped:
Days
The run each one joins
sorted(days)
3 4 4 5 8 9 12
A A B B C C D
sorted(set(days))
3 4 5 8 9 12
A A A B B C
The second 4 is not one after the last run's end, which is already 4. So a walk that keeps repeats starts a new run there, and splits (3, 5) into (3, 4) and (4, 5).
Sorting is O(d log d) for d days, and the walk is O(d).
In the editor, write runs(days): sort the free days with the repeats dropped, walk them once, and return each run as a closed (first, last) tuple.
Pick an answer above to see the rest
Instructions
1
days holds the days someone is free, as integers in any order, possibly repeated. Finish runs(days): return each run of days in a row as a closed (first, last) tuple, both days included, in order. {3, 4, 5, 8, 9, 12} gives [(3, 5), (8, 9), (12, 12)].