Sort time by start time
.
Then check if next time slot start time
is higher than current slot end time
.
TimeSlot[] slots;
sort(slots, slots.start_time);
for(i = 0 to (slots.length - 1)){
if(slots[i].end_time > slots[i + 1].start_time) reportConflict();
}
It works in time O(n log n)
where n
is number of time slots
If you need to find all conflicted pairs then you need to modify algorithm:
TimeSlot[] slots;
sort(slots, slots.start_time);
for(i = 0 to (slots.length - 1)){
int j = i + 1;
while(j < (slots.length - 1) and slots[i].end_time > slots[j].start_time){
reportConflict(i, j);
++j;
}
}
It works in time O((n log n) + c)
where n
is number of time slots and c
is number of conflicts
If you need only number of overlaps there is better algorithm using binary search:
TimeSlot[] slots;
int overlapsNumber = 0;
sort(slots, slots.start_time);
for(i = 0 to (slots.length - 1)){
int j = BinarySearch(slots, i);
overlapsNumber += (j - i);
}
//Finds index j which is the greatest index that slots[j].start_time < slots[i].end_time
int BinarySearch(TimeSlot[] sortedSlots, int pos){
int b = pos, e = sortedSlots.length - 1;
int ans = b;
while(b < e){
int mid = (e + b) / 2;
if(sortedSlots[mid].start_time < sortedSlots[pos].end_time){
ans = mid;
b = mid + 1;
} else {
e = mid - 1;
}
}
return ans;
It works in time O(n log n)
.