Many times when we are programming , we repeat the same calculations several times, and not in the most efficient way. This is an example, the calculation of the overlaping between dates, times or segments.
I think that this schema illustrates really well the trick, and the most efficient (reasoned) solution: