Whether this is the most efficient or quickest, I'm unsure, but this is how I would do it. If it turned out to be a bottleneck, then and only then would I look into optimising further:
You ensure that the first range starts earlier (or at the same time) by swapping the ranges if necessary.
Then, you can detect overlap if the other range start is less than or equal to the first range end (if ranges are inclusive, containing both the start and end times) or less than (if ranges are inclusive of start and exclusive of end).
Assuming inclusive at both ends, there's only four possibilities of which one is a non-overlap:
|----------------------| range 1
|---> range 2 overlap
|---> range 2 overlap
|---> range 2 overlap
|---> range 2 no overlap
The endpoint of the range 2 doesn't enter into it. So, in pseudo-code:
def doesOverlap (r1,r2):
if r1.s > r2.s:
swap r1, r2
if r2.s > r1.e:
return false
return true
If the ranges are inclusive at the start and exclusive at the end, you just have to replace >
with >=
in the second if
statement:
|----------------------| range 1
|---> range 2 overlap
|---> range 2 overlap
|---> range 2 no overlap
|---> range 2 no overlap
You greatly limit the number of checks you have to make because you remove half of the problem space early by ensuring range 1 never starts after range 2.