Sub topic 2
Testing Whether Two Intervals Overlap
This chapter assumes you can read short Python functions and compare numbers. It also assumes you know what a closed interval [low, high] is, as covered in the previous chapter. You don't need any tree knowledge yet. The overlap test is the one predicate that every interval tree operation relies on, so it's worth getting exactly right.
The Question
Given two closed intervals a = [a_lo, a_hi] and b = [b_lo, b_hi], do they share at least one point? Each interval is a set of all numbers between its endpoints, including the endpoints. The question is whether the intersection of those two sets is non-empty.
You could compare endpoints case by case. Instead, ask the opposite question: when do the intervals not overlap? That case is much shorter.
Deriving the Test from the Disjoint Cases
Two intervals fail to share a point in exactly two ways:
alies entirely to the left ofb, soa_hi < b_lo.alies entirely to the right ofb, sob_hi < a_lo.
Any other arrangement leaves some gap-free contact between them. So the intervals overlap exactly when neither condition holds:
overlap = not (a_hi < b_lo or b_hi < a_lo)Apply De Morgan's law, which turns not (P or Q) into (not P) and (not Q). Negating < gives >=, so:
overlap = a_hi >= b_lo and b_hi >= a_loRewritten with the low endpoint on the left, this is the form used throughout the rest of the tutorial:
def overlaps(a, b):
# a and b are closed intervals given as (low, high) with low <= high
return a[0] <= b[1] and b[0] <= a[1]
print(overlaps((15, 20), (10, 30))) # True
print(overlaps((5, 8), (9, 12))) # False
print(overlaps((5, 9), (9, 12))) # True, closed intervals sharing an endpoint overlapIn words: each interval must start no later than the other one ends.
The Arrangements the Test Covers
The two-comparison test handles every way two intervals can be positioned. The table lists them, using a = [a_lo, a_hi] and b = [b_lo, b_hi].
| Arrangement | Example (a, b) | `a_lo <= b_hi` | `b_lo <= a_hi` | Overlap |
|---|---|---|---|---|
| a entirely left of b | (1, 3), (5, 8) | True | False | No |
| a entirely right of b | (10, 12), (5, 8) | False | True | No |
| a touches b at one point | (1, 5), (5, 8) | True | True | Yes |
| a overlaps b's start | (1, 6), (5, 8) | True | True | Yes |
| a contains b | (1, 10), (5, 8) | True | True | Yes |
| b contains a | (6, 7), (5, 8) | True | True | Yes |
| identical intervals | (5, 8), (5, 8) | True | True | Yes |
Notice that the three overlapping arrangements "partial", "contains", and "contained" all produce the same answer from the same two comparisons. The test never needs to know which kind of overlap it found. This matters later, because the tree search compares a query against many nodes and only wants a yes or no.
Why the Test Is Symmetric
Swap a and b in the final formula. You get b_lo <= a_hi and a_lo <= b_hi, which is the same two comparisons in the opposite order. So overlaps(a, b) == overlaps(b, a) always. You can pass the query and the stored interval in either order.
Checking the Predicate by Brute Force
A one-line boolean formula is easy to get subtly wrong, for example by writing < where you meant <=. For integer endpoints you can check it against the definition. Build the set of points in each interval and test whether the sets intersect.
def overlaps(a, b):
return a[0] <= b[1] and b[0] <= a[1]
def overlaps_by_points(a, b):
# Definition: the intervals share at least one integer point.
points_a = set(range(a[0], a[1] + 1))
points_b = set(range(b[0], b[1] + 1))
return len(points_a & points_b) > 0
intervals = [(lo, hi) for lo in range(0, 7) for hi in range(lo, 7)]
mismatches = 0
for a in intervals:
for b in intervals:
if overlaps(a, b) != overlaps_by_points(a, b):
mismatches += 1
print(len(intervals) ** 2, "pairs checked")
print(mismatches, "mismatches")This prints 784 pairs checked and 0 mismatches. The check works for integers because two closed integer intervals share a real point exactly when they share an integer point. The endpoints of the overlap region are themselves integers.
Getting the Intersection Itself
When two intervals overlap, the shared region is itself a closed interval. It starts at the larger low endpoint and ends at the smaller high endpoint.
def intersection(a, b):
lo = max(a[0], b[0])
hi = min(a[1], b[1])
return (lo, hi) if lo <= hi else None
print(intersection((15, 20), (10, 30))) # (15, 20)
print(intersection((5, 9), (9, 12))) # (9, 9)
print(intersection((5, 8), (9, 12))) # NoneThe condition lo <= hi here is the overlap test in disguise. max(a_lo, b_lo) <= min(a_hi, b_hi) holds exactly when all four cross-comparisons hold, and two of those (a_lo <= a_hi and b_lo <= b_hi) are already guaranteed by the input. Interval trees only need the yes/no answer, so they use the shorter overlaps.
Edge Cases That Cause Bugs
Touching Endpoints
For closed intervals, (5, 9) and (9, 12) overlap at the single point 9. If your application treats that as not overlapping, you have a different interval type, covered next.
Half-Open Intervals
Many systems, such as Python's range and most calendar libraries, use half-open intervals [low, high), where low is included and high is excluded. Then [5, 9) and [9, 12) do not share a point. The test uses strict inequalities:
def overlaps_half_open(a, b):
# a and b are half-open intervals [low, high) with low < high
return a[0] < b[1] and b[0] < a[1]
print(overlaps_half_open((5, 9), (9, 12))) # False
print(overlaps_half_open((5, 10), (9, 12))) # TrueDegenerate Intervals
A point such as (7, 7) is a valid closed interval, and the test handles it with no special case. overlaps((7, 7), (5, 9)) is True, and overlaps((7, 7), (8, 9)) is False. A half-open interval with low == high is empty, so the half-open test is only meaningful when low < high.
Invalid Input
The test assumes low <= high for both intervals. If you pass (9, 5), the formula still returns a boolean, but the result has no meaning. Validate intervals once, when they enter your structure, rather than inside the test.
Floats
The test works for floating-point endpoints, but comparison of computed values can be off by rounding error. Two intervals that should touch, such as (0.1 + 0.2, 1.0) and (0.0, 0.3), may compare as disjoint because 0.1 + 0.2 is 0.30000000000000004. The value float('nan') makes every comparison False, so a NaN endpoint always yields "no overlap". Reject NaN when inserting.
Where This Test Goes Next
The overlap test is a constant-time operation: two comparisons, no loops. A naive search applies it to every stored interval. An interval tree applies it to a handful of nodes along one path. The next chapters define the query problem precisely and show why the cost of applying this test to every interval becomes a problem.
Exercise
Decide whether each pair of closed intervals overlaps, then give the reason using the two-comparison test: (3, 7) and (7, 7); (2, 4) and (5, 6); (1, 10) and (4, 5).
Show answer
(3, 7) and (7, 7) overlap: 3 <= 7 and 7 <= 7 are both true, and they share the point 7. (2, 4) and (5, 6) do not overlap: 2 <= 6 is true, but 5 <= 4 is false, so the first interval ends before the second starts. (1, 10) and (4, 5) overlap: 1 <= 5 and 4 <= 10 are both true, because the second interval is contained in the first.
Exercise
Change overlaps so that intervals touching at exactly one endpoint do not count as overlapping, and state which kind of interval this models. What does your version return for (5, 9) and (9, 12)?
Show answer
Replace both <= with <: return a[0] < b[1] and b[0] < a[1]. This models half-open intervals [low, high), where the high endpoint is excluded and low < high. For (5, 9) and (9, 12) it returns False, because 9 < 9 is false.