I’m going to be as clear as I can.
I have an event that have two times, start and end. (Times are in 24h format)
For example, this event starts at 8, and finishes at 12.
With this event, I have a list of person with their work schedule.
Here’s an example :
- Person 1 : From 8:00 to 10:00
- Person 2 : From 10:00 to 12:00
- Person 3 : From 6:00 to 15:00
- Person 4 : From 8:00 to 9:00
- Person 5 : From 9:30 to 12:00
Now, I need to know how many people, at minimum, I have through the whole event.
In my case, it will be 2, because :
- Person 1 & Person 2 complement each other
- Person 3 will always be present
- There is a gasp between person 4 & 5, between 9:00 and 9:30, so during this time, no one between Person 4 & 5 will be present.
If I explain this with times :
- From 8:00 to 9:00 : Person 1, 3, 4
- From 9:00 to 9:30 : Person 1, 3
- From 9:30 to 10:00 : Person 1, 3, 5
- From 10:00 to 12:00 : Person 2, 3, 5
Most of the time, the event will have 3 person, but the lowest if 2.
How can I get this number using an algorithm, I can’t make my mind with this.
I thought about converting the time in minutes (I won’t go under the minute), set the range at the event times (from 8*60 to 12*60), and add each person presence as a new range, and then count for each minutes, how many slice there is (1 slice = 1 person). But I feel this isn’t efficient, because I will have to count the slices for 4*60 minutes :/ (from 8 -> 12).
How would you do ?
Take the start and end times for person number
i, and name thems_iande_i.Put all of these in a list,
times. Then do the following:The running time for this is found as follows:
Let
nbe the number of people.We spend
O(n lg n)time doing the sorting, as we only have2ntimes to sort.We then spend
O(n)time iterating through the times, doing constant work.Overall,
O(n lg n). Note that this running time is completely independent of how large an interval of time it spans over, and is only dependent on how many people you’re dealing with.This is a form of sweep line algorithm. We sweep through the times, only stopping at the points of interest (the
s_iande_is.)Note, the reason we sort the
s_is beforee_js in case of a tie, is as follows:If we don’t, then imagine we have two people: Bob is here from 8-10, Alice is here from 10-12. We might then, if we don’t do careful sorting, get the following list of times:
If we sort it like this, then it looks like there are no people left after Bob leaves at 10. However, Alice is there, since she arrives at the same time. Thus, to prevent this, we sort it such that starting times are before ending times, in case of a tie: