You are given 'n' appointments. Each appointment contains startime and endtime. You have to return all conflicting appointments efficiently starttime and endtime can range from a few min to few years.
Approach:
E5: 4 : 12
E3: 11 : 24
E1: 13 : 15
E2: 18 : 20
E4: 19: 27
Now take the end time of first Event (E5) ie 12 and check in the start time the first event whose start time is greater than 12, in the above example E1 - with start time 13 is the event.
Now we can safely say that all the events less than E1 and greater than E5 are conflicting with E5 - which is E3 in our case.
With the same above logic, E3 is conflicting with E1, E2 and E4.
Time complexity = O(nlogn) for sorting the events on start time + O(nlogn) for searching a all the conflicting events for a given event Ei (1 <= i <= n).
So total time complexity: O(nlogn)
Output of the below code:
Events sorted with start time:
5: 4:12
3: 11:24
1: 13:15
2: 18:20
4: 19:27
Conflicts are:
1 <> 3
2 <> 3 4
3 <> 5 1 2 4
4 <> 3 2
5 <> 3
Approach:
Suppose there are 5 events:
E1 => 13 : 15
E2 => 18 : 20
E3 => 11 : 24
E4 => 19 : 27
E5 => 4 : 12
Now sort the events with start time:
E5: 4 : 12
E3: 11 : 24
E1: 13 : 15
E2: 18 : 20
E4: 19: 27
Now take the end time of first Event (E5) ie 12 and check in the start time the first event whose start time is greater than 12, in the above example E1 - with start time 13 is the event.
Now we can safely say that all the events less than E1 and greater than E5 are conflicting with E5 - which is E3 in our case.
With the same above logic, E3 is conflicting with E1, E2 and E4.
Time complexity = O(nlogn) for sorting the events on start time + O(nlogn) for searching a all the conflicting events for a given event Ei (1 <= i <= n).
So total time complexity: O(nlogn)
Output of the below code:
Events sorted with start time:
5: 4:12
3: 11:24
1: 13:15
2: 18:20
4: 19:27
Conflicts are:
1 <> 3
2 <> 3 4
3 <> 5 1 2 4
4 <> 3 2
5 <> 3
Thank you so much!
ReplyDelete