Checking whether two intervals overlap is a standard programming problem, but also a good exercise in careful reasoning. To be more specific, I want to derive a simple formula that decides whether two intervals \([a_1,b_1], [a_2,b_2]\) overlap. Let’s assume that these are proper intervals, i.e. \(a_1 \leq b_1, a_2 \leq b_2\). My reasoning is as follows:
Consider the case where the intervals are disjoint (no overlap). Let’s call this scenario \( A \). Clearly, in this case one interval has to appear before the other. More precisely, the end of the first interval has to be smaller than the beginning of the second interval. And of course the converse is true too: If the end of one interval is smaller than the beginning of the second, then they are definitely disjoint. In summary:
Two intervals either overlap or they do not. If we use \( B \) to denote the scenario where the intervals overlap, we have:
Putting together the first two points and applying some boolean algebra yields the formula:
So the code I ended up using in my case was
b_1 >= a_2 && b_2 >= a_1.