Sub topic 9
Searching for One Overlapping Interval
This chapter assumes you can read the augmented tree from the previous chapters. Each node stores an interval (lo, hi), the tree is ordered by lo, and each node's max field holds the largest hi in its subtree. Here you will use that field to find one stored interval that overlaps a query interval, without visiting every node.
The Problem
You have a tree of intervals and a query interval [lo, hi]. You want any one stored interval that overlaps the query, or a signal that none does.
The overlap test from earlier is the building block:
def overlaps(a, b):
return a[0] <= b[1] and b[0] <= a[1]Applying it to every node costs O(n). The max field lets you decide at each node which child to enter and skip the other one completely.
The Search Procedure
At each node, the search does two things:
- Check whether the node's own interval overlaps the query. If it does, return it.
- Otherwise choose one child to descend into. Go left if the left child exists and its
maxis at least the query'slo. Go right in every other case.
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 NoneThe loop is iterative, so it uses O(1) extra space. It never visits more than one child per level, so the work is proportional to the height of the tree.
Why `left.max >= lo` Is the Test
The test compares the left subtree's max to the query's low endpoint, because of what each outcome tells you.
- If
left.max >= lo, some interval in the left subtree ends at or after the query starts. That interval might overlap the query, so the left subtree is worth entering. - If
left.max < lo, every interval in the left subtree ends before the query starts. None of them can overlap, so the search can ignore the left subtree and go right.
When the search goes left, the right subtree is discarded even though it might also contain overlaps. That is safe because the search only has to return one interval. The next chapter proves that going left never causes a miss. For now, the key point is that the max field makes the left subtree's answer available in constant time.
Tracing the Example
Build the tree from the spine's data:
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
root = None
for lo, hi in [(15, 20), (10, 30), (17, 19), (5, 20), (12, 15), (30, 40)]:
root = insert(root, lo, hi)
print(find_overlap(root, 21, 23)) # (10, 30)
print(find_overlap(root, 35, 36)) # (30, 40)
print(find_overlap(root, 45, 50)) # NoneThe resulting tree, with each node's max in brackets, looks like this:
| Node | Interval | max | Left child | Right child |
|---|---|---|---|---|
| A | (15, 20) | 40 | B | C |
| B | (10, 30) | 30 | D | E |
| C | (17, 19) | 40 | none | F |
| D | (5, 20) | 20 | none | none |
| E | (12, 15) | 15 | none | none |
| F | (30, 40) | 40 | none | none |
Query (21, 23). At A, (15, 20) does not overlap because 21 <= 20 is false. A's left child B has max = 30, and 30 >= 21, so the search goes left. At B, 10 <= 23 and 21 <= 30, so (10, 30) is returned.
Query (35, 36). At A there is no overlap. B's max is 30, and 30 >= 35 is false, so the search goes right to C. C's interval (17, 19) does not overlap, and C has no left child, so the search goes right to F. F's interval (30, 40) overlaps, so it is returned.
Query (45, 50). The search visits A, C, and F, finds no overlap, and runs off the tree. It returns None.
Edge Cases
Empty tree. The loop condition fails immediately and the function returns None.
Closed intervals touching at an endpoint. The query (20, 25) against a stored (15, 20) overlaps, because both comparisons use <=. The same rule applies to the max test: left.max >= lo is non-strict. Writing > would make the search skip a left subtree whose only candidate touches the query at one point, and the function would return None or a wrong answer for closed intervals.
Several overlaps exist. The function returns whichever one it reaches first. That may not be the one with the smallest lo or the largest hi. If you need a specific one, such as the leftmost, you need a different traversal. The next chapters cover reporting every overlap.
A query that contains a stored interval, or the reverse. The overlap test handles containment in both directions, because it only checks that each interval starts no later than the other ends.
Left child missing. The node.left is not None check matters. Without it, node.left.max raises AttributeError. Some implementations store a sentinel node with max = -infinity instead of using None. Both designs work, and the comparison then fails naturally.
Common Mistakes
- Deciding direction by
node.loornode.hialone. The tree is ordered bylo, sonode.losays nothing about whether the left subtree has intervals that reach far to the right. Onlyleft.maxcarries that information. - Testing
node.maxinstead ofnode.left.max. The node's ownmaxincludes its right subtree and itself, so it is always at leastnode.hi. Using it would send the search left into subtrees that have nothing. - Stale
maxvalues. The search trusts the field. If an insert, delete, or rotation forgets to update it, the search can wrongly skip a subtree and returnNonewhen an overlap exists. When the search gives a wrong answer, check the invariant before you check the search. - Mixing open and closed intervals. The code here is for closed intervals. For half-open intervals
[lo, hi), every<=that compares against an upper endpoint must become<, in both the overlap test and themaxtest.
Cost
Each loop iteration does constant work and moves one level down, so the cost is O(h), where h is the height of the tree. In a balanced tree, h is O(log n), so a search takes O(log n) time. In an unbalanced tree built from sorted input, h can reach n and the search degrades to O(n). The chapter on balancing shows how to keep h small. The search itself uses O(1) extra space.
The None result is also fast. Failing to find an overlap does not require checking everything, because the max field has already ruled out whole subtrees along the path.
Exercise
A tree stores (20, 25) at the root with max 60, a left child (10, 12) with max 18, and a right child (30, 60) with max 60. You call find_overlap(root, 13, 15). Which nodes does the search visit, and what does it return?
Show answer
It visits the root (20, 25) and then the left child (10, 12), and returns None. At the root, 20 <= 15 is false, so there is no overlap. The left child's max is 18, and 18 >= 13, so the search goes left. At (10, 12), 10 <= 15 is true but 13 <= 12 is false, so there is no overlap. The node has no left child, so the search goes right, finds nothing, and returns None. The right subtree at the root is never visited, which is correct because every interval there starts at 30 or later, after the query ends at 15.
Exercise
Why does changing node.left.max >= lo to node.left.max > lo break the search for closed intervals? Give a concrete example.
Show answer
With the strict comparison, a left subtree whose largest high endpoint equals the query's low endpoint is skipped, even though a closed interval ending at that value touches the query and therefore overlaps it. Example: the root is (15, 20) with max 20, and its only child, on the left, is (5, 9). Querying (9, 12) gives left.max = 9, and 9 > 9 is false, so the search goes right, finds nothing, and returns None. The correct answer is (5, 9), because the closed intervals share the point 9.