Came across this question in an interview blog. Given free-time schedule in the form (a - b) i.e., from 'a' to 'b'
of n
people, print all time intervals where all n
participants are available. It's like a calendar application suggesting possible meeting timinings.
Example:
Person1: (4 - 16), (18 - 25)
Person2: (2 - 14), (17 - 24)
Person3: (6 - 8), (12 - 20)
Person4: (10 - 22)
Time interval when all are available: (12 - 14), (18 - 20).
Please share any known optimal algorithm to solve this problem.
I am thinking of the following solution.
Create a
currentList
of intervals that contain one interval from each person. InitiallycurrentList = [4-16, 2-14, 6-8, 10-22]
.Look for the
max_start
andmin_end
incurrentList
and output(max_start, min_end)
ifmax_start < min_end
; Update all intervals incurrentList
to havestart
value asmin_end
. Remove the interval that hasmin_end
fromcurrentList
and add the next entry in that person's list tocurrentList
.If
max_start >= min_end
in previous step, update all intervals incurrentList
to havestart
value asmax_start
. If for any intervali
,end > start
, replace that interval incurrentList
with the next interval of the corresponding person.
Based on the above idea, it will run as below for the given example:
currentList = [4-16, 2-14, 6-8, 10-22] max_start=10 >= min_end=8
update start values to be 10 and replace 6-8 with next entry 12-20.
currentList = [10-16, 10-14, 12-20, 10-22] max_start=12 <= min_end=14
add max_start-min_end to output and update start values to 14. Output=[12-14]
currentList = [14-16, 17-24, 14-20, 14-22] max_start=17 >= min_end=16
update start values to be 17 and replace 14-16 with 18-25
currentList = [18-25, 17-24, 17-20, 17-22] max_start=18 <= min_end=20
add max_start-min_end to output and update start values to 20. Output=[12-14, 18-20]
currentList = [20-25, 2-24, - , 2-22]
Terminate now since there are no more entry from person 3.
I have not implemented the above though. I am thinking of a min-heap and max-heap to get the min and max at any point. But I am concerned about updating the start values because updating the heap may become expensive.