FInd overlapping appointments in O(n) time?

前端 未结 5 838
独厮守ぢ
独厮守ぢ 2020-12-12 18:16

I was recently asked this question in an interview. Even though I was able to come up the O(n²) solution, the interviewer was obsessed with an O(<

5条回答
  •  萌比男神i
    2020-12-12 19:06

    The general solution to this problem is not possible in O(n).

    At a minimum you need to sort by appointment start time, which requires O(n log n).

    There is an O(n) solution if the list is already sorted. The algorithm basically involves checking whether the next appointment is overlapped by any previous ones. There is a bit of subtlety to this one as you actually need two pointers into the list as you run through it:

    • The current appointment being checked
    • The appointment with the latest end time encountered so far (which might not be the previous appointment)

    O(n) solutions for the unsorted case could only exist if you have other constraints, e.g. a fixed number of appointment timeslots. If this was the case, then you can use HashSets to determine which appointment(s) cover each timeslot, algorithm roughly as follows:

    • Create a HashSet for each timeslot - O(1) since timeslot number is a fixed constant
    • For each appointment, store its ID number in HashSets of slot(s) that it covers - O(n) since updating a constant number of timeslots is O(1) for each appointment
    • Run through the slots, checking for overlaps - O(1) (or O(n) if you want to iterate over the overlapping appointments to return them as results)

提交回复
热议问题