1

You are given 'n' appointments. Each appointment contains startime and endtime. You have to retun all conflicting appointments efficiently starttime and endtime can range from a few min to few years. I saw the post: FInd overlapping appointments in O(n) time? which is very similar to this. But a doubt remains.

My question is that if we have a sorted schedule given, say : (6:30-6:35), (6:40-7:10) (7:25-7:40), (7:35-7:50) and so on.

Can we not traverse the schedule list and make sure that the next appointment should begin ONLY after the previous one is over? In that case we're applying a very tight bound on the possible time for scheduling an appointment. In this example, we know that the appointment beginning at 7:35 is before last appointment ends (7:40) so it is a conflict. Do we really need to complicate the solution by creating a tree or hash map as mentioned in the most rated solution in link for similar question?

Please point out cases which can bypass this check and prove this condition invalid.

Community
  • 1
  • 1
user1071840
  • 3,522
  • 9
  • 48
  • 74
  • Thank you for the quick response. I wanted to make sure because the solution stated that, "The algorithm basically involves checking whether the next appointment is overlapped by _**any**_ previous ones." – user1071840 Sep 24 '12 at 02:56
  • You do have to check *any* previous ones. The appointment doesn't necessarily overlap the one immediately prior, eg: `(0, 5), (2, 3), (4, 8)` The third appointment overlaps the first one but not the second. However, you don't actually have to compare each appointment to every other appointment to achieve this, you can just keep track of the latest end time you have seen so far. – verdesmarald Sep 24 '12 at 03:06
  • But if we just need to find out if there are any overlaps at all, we'll stop at the second one itself. You are right when you say, "The third appointment overlaps the first one but not the second. " but second one begins before first has ended so we never really go to the third. – user1071840 Sep 24 '12 at 03:21
  • Correct, however your question title is "find **all** conflicting appointments", not find the first one. :) – verdesmarald Sep 24 '12 at 04:03

2 Answers2

1

In the linked answer, the list appointments is not sorted, hence the more complicated solution. You are correct that if the appointments are sorted you can just traverse the list and keep track of the latest end time seen so far.

Also, note that sorting the list is O(n lg n), so you can't just sort it and then traverse it if you want an O(n) solution.

verdesmarald
  • 11,646
  • 2
  • 44
  • 60
0

Of course the solution can be performed in O(n) time if as you say "we have a sorted schedule given." The question you referenced is assuming the times are NOT sorted.

aquinas
  • 23,318
  • 5
  • 58
  • 81