Sub topic 10
Why the Search Never Misses an Overlap
This chapter assumes you have read the previous chapters. You should know the overlap test, the BST ordering by low endpoint, and the max-endpoint invariant. You should also be comfortable reading short Python.
The search from the last chapter looks too aggressive. At each node it chooses one child and discards the other subtree, and it never looks back. Here is why that is safe.
The search being justified
def find_overlap(node, lo, hi):
# Returns one stored interval overlapping [lo, hi], or None.
while node is not None:
if node.lo <= hi and lo <= node.hi:
return (node.lo, node.hi)
if node.left is not None and node.left.max >= lo:
node = node.left
else:
node = node.right
return NoneEach loop iteration makes one of three decisions:
- The current node overlaps the query, so return it.
- The left subtree has
max >= lo, so move left. - Otherwise move right.
The correctness claim is this: if any stored interval overlaps the query, the loop finds one. An interval that is skipped can never be the only overlap. We prove this for decisions 2 and 3. Decision 1 needs no proof.
The two facts the proof uses
Two properties of the tree carry the whole argument.
- BST order. Every interval in a node's left subtree has a low endpoint smaller than the node's low endpoint. Every interval in the right subtree has a low endpoint at least as large. This holds because
insertsendslo < node.loleft and everything else right. - Max invariant.
node.maxis the largest high endpoint among all intervals in that node's subtree.
The overlap test also has a useful negation. Two intervals i and q fail to overlap exactly when i.lo > q.hi or q.lo > i.hi. That is, i starts after q ends, or i ends before q starts. There are only two ways to miss.
Case 1: the left max is below the query's low endpoint
Suppose node.left is empty or node.left.max < lo. Every interval in the left subtree has hi <= left.max < lo. Each of them ends before the query starts, so none overlaps. Going right discards only intervals that cannot match. The node itself was already tested, so nothing is lost.
Case 2: the left max is at least the query's low endpoint
This case is the subtle one. Suppose node.left.max >= lo. By the max invariant, some interval i in the left subtree has i.hi = left.max >= lo. There are two sub-cases.
Sub-case A: i overlaps the query. Then the left subtree contains an overlap. Going left is correct, and the search will find an overlap there by the same reasoning applied recursively.
Sub-case B: i does not overlap the query. We know i.hi >= lo, so i does not end before the query starts. The only remaining way to miss is i.lo > hi. The interval i is in the left subtree, so by BST order i.lo < node.lo. Chaining the inequalities gives:
hi < i.lo < node.lo
Every interval in the right subtree has a low endpoint of at least node.lo, which is greater than hi. So every right-subtree interval starts after the query ends, and none can overlap. The node itself was already tested, and it also has lo > hi.
So in sub-case B the whole right subtree holds no overlap. Going left cannot miss anything on the right. Whatever overlap exists must be in the left subtree, or there is none. In both sub-cases, going left is safe.
The two cases together form the invariant that the loop preserves: if any interval in the tree overlaps the query, then one lies in the subtree we are currently standing at, or it was the node already returned. The loop ends either at a returned interval or at None, and None is only reached when the invariant says no overlap exists.
A worked trace
Use the tree from the earlier chapters, built from (15, 20), (10, 30), (17, 19), (5, 20), (12, 15), (30, 40). The root is (15, 20) with max = 40. Its left child is (10, 30) with max = 30.
Query [21, 23]:
- Root
(15, 20):15 <= 23is true, but21 <= 20is false, so no overlap.left.max = 30 >= 21, so go left. - Node
(10, 30):10 <= 23and21 <= 30are both true. Return(10, 30).
Query [45, 50]:
- Root: no overlap.
left.max = 30 < 45, so Case 1 applies and we go right. - Node
(17, 19): no overlap, and it has no left child. Go right. - Node
(30, 40):45 <= 40is false, so no overlap. No left child and no right child. ReturnNone.
The second query hits Case 1 at the root. Its whole left subtree is discarded because every interval there ends at or before 30.
Checking the proof against brute force
A proof is only as good as its assumptions, such as the BST ordering and an accurate max. A randomized test compares the tree search with a linear scan. This code is complete and runs as shown.
import random
class Node:
def __init__(self, lo, hi):
self.lo = lo
self.hi = hi
self.max = hi
self.left = None
self.right = None
def insert(node, lo, hi):
if node is None:
return Node(lo, hi)
if lo < node.lo:
node.left = insert(node.left, lo, hi)
else:
node.right = insert(node.right, lo, hi)
node.max = max(node.max, hi)
return node
def find_overlap(node, lo, hi):
while node is not None:
if node.lo <= hi and lo <= node.hi:
return (node.lo, node.hi)
if node.left is not None and node.left.max >= lo:
node = node.left
else:
node = node.right
return None
def brute(items, lo, hi):
return any(a <= hi and lo <= b for a, b in items)
random.seed(1)
for _ in range(2000):
items, root = [], None
for _ in range(random.randint(0, 15)):
a = random.randint(0, 50)
b = a + random.randint(0, 15)
items.append((a, b))
root = insert(root, a, b)
qlo = random.randint(0, 60)
qhi = qlo + random.randint(0, 10)
found = find_overlap(root, qlo, qhi)
assert (found is not None) == brute(items, qlo, qhi)
if found is not None:
assert found[0] <= qhi and qlo <= found[1]
print("ok")The first assertion checks that the search and the scan agree on whether an overlap exists. This is the "never misses" property. The second checks that any returned interval really overlaps.
How the proof breaks
Each assumption maps to a bug you may meet in practice.
| Broken assumption | Symptom |
|---|---|
| `max` not updated after an insert or delete | Case 1 discards a subtree that does hold an overlap, so the search returns `None` wrongly. |
| `max` not recomputed after a rotation | Same failure, but only after rebalancing. |
| Tree ordered by high endpoint instead of low | Sub-case B fails, because `i.lo < node.lo` no longer holds. |
| Open intervals with a closed-interval test (or the reverse) | Touching intervals such as `(5, 9)` and `(9, 12)` are handled inconsistently. |
Rotations are the most common culprit. After a rotation, recompute max for the demoted node first, then for the promoted node, each as the maximum of its own hi and its children's max values.
What the proof does not give you
The proof shows that one overlap is found if one exists. It says nothing about which overlap is returned, and it does not enumerate all of them. The same query on the example tree could return a different interval if the tree shape were different. Reporting every overlap needs a different traversal, and the next chapter covers it. That traversal prunes by the same two facts, but it must sometimes visit both children.
Exercise
In the search, suppose node.left.max >= lo, the query does not overlap the left subtree's interval i that achieves that max, and node.lo <= hi. What does this tell you about i, and why can the right subtree be discarded?
Show answer
Since i.hi >= lo, the only way i misses the query is i.lo > hi. By BST order i.lo < node.lo, so hi < i.lo < node.lo. That contradicts node.lo <= hi, so this situation cannot occur: if node.lo <= hi, the interval i must overlap the query. When node.lo > hi, every right-subtree interval has lo >= node.lo > hi, so none overlaps and the right subtree can be discarded.
Exercise
A bug leaves node.max stale after a rotation, so it is smaller than the true maximum in its subtree. Which case of the proof fails, and what wrong output can the search produce?
Show answer
Case 1 fails. A stale, too-small left.max can fall below lo even though the left subtree holds an interval with hi >= lo. The search then goes right and discards that subtree, and it can return None when an overlap exists.