Sub topic 11
Reporting Every Overlapping Interval
This chapter assumes you have read the earlier chapters of this tutorial. You should know the overlap test for closed intervals, the node layout with a max field, and find_overlap, which returns a single stored interval that overlaps the query. Here you will extend the search so it returns all of them.
From One Answer to Every Answer
find_overlap can commit to one branch at each node. It goes left when node.left.max >= lo and right otherwise. That works because it only needs one overlap, and the earlier correctness argument shows that if the left subtree cannot supply one, the right subtree is the only place left.
Reporting every overlap removes that shortcut. Both subtrees can hold overlapping intervals at the same time, so the search must be a full traversal that skips only the parts that provably contain nothing. Two facts about the tree justify the skipping.
- The
maxfield bounds a whole subtree from above. Ifnode.max < lo, every interval in that subtree ends before the query begins. None of them can overlap, so the whole subtree can be skipped. - The BST order on
lobounds the right subtree from below. Every interval innode.righthas a low endpoint at leastnode.lo. Ifnode.lo > hi, all of them start after the query ends, so the right subtree can be skipped.
There is no matching rule for skipping the left subtree on low endpoints. Left intervals have smaller lo values, so they can only start earlier. The max test is the only thing that rules them out.
The Algorithm
The traversal is an in-order walk with two guards. It visits the left subtree, tests the current node, then visits the right subtree. Reporting in this order gives results sorted by low endpoint as a side effect.
class Node:
def __init__(self, lo, hi):
self.lo = lo
self.hi = hi
self.max = hi # largest high endpoint in this node's subtree
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_all(node, lo, hi, out):
# Appends every stored interval overlapping [lo, hi] to out.
if node is None or node.max < lo:
return
find_all(node.left, lo, hi, out)
if node.lo <= hi and lo <= node.hi:
out.append((node.lo, node.hi))
if node.lo <= hi:
find_all(node.right, lo, hi, out)
root = None
for lo, hi in [(15, 20), (10, 30), (17, 19), (5, 20), (12, 15), (30, 40)]:
root = insert(root, lo, hi)
result = []
find_all(root, 14, 16, result)
print(result) # [(5, 20), (10, 30), (12, 15), (15, 20)]The result is already in order of low endpoint, so the earlier chapter's example needed sorted only to be safe. The in-order walk produces sorted output without it.
The function returns nothing and writes into the list out. This avoids building and concatenating intermediate lists at every level of recursion.
Tracing the Example
The tree built above has (15, 20) at the root with max = 40. Its left child is (10, 30) with max = 30. That node has children (5, 20) and (12, 15). The root's right child is (17, 19) with max = 40, and it has a right child (30, 40). The query is [14, 16].
The walk goes through these steps:
- At the root,
40 >= 14, so the search continues. It descends left first. - At
(10, 30),30 >= 14, so it continues. It descends left again to(5, 20). - At
(5, 20),20 >= 14holds, and the node overlaps, so it is reported. Both children areNone. - Back at
(10, 30), the node overlaps[14, 16]and is reported. Since10 <= 16, the search enters the right child(12, 15), which is also reported. - Back at the root,
(15, 20)overlaps and is reported. Since15 <= 16, the search enters(17, 19). - At
(17, 19), the node does not overlap because17 > 16. The right guard17 <= 16is false, so(30, 40)is never entered.
Six intervals are stored and five nodes were visited. On larger trees, with queries that overlap only a few intervals, the saving is far greater.
Edge Cases
- Closed endpoints. The prune test is
node.max < lo, strictly less than. If it used<=, a query[30, 35]would wrongly skip a subtree whose largest endpoint is exactly 30, and the interval(10, 30)would be lost. Because intervals are closed, touching at one point counts as overlap. - An empty result. A query beyond every stored interval, such as
[41, 50]on the tree above, returns at the root, since40 < 41. The cost is one comparison. - A query that covers everything. The query
[0, 100]reports all six intervals and visits every node. No pruning rule can help here, because every interval really is part of the answer. - Duplicate low endpoints.
insertsends equal keys to the right subtree. The right guard isnode.lo <= hi, which is true whenever the node'sloequals the query'shi, so equal-key intervals are still reached. - Recursion depth. The recursion goes as deep as the tree is tall. On a balanced tree this is fine. On an unbalanced tree built from sorted input, the height can reach the number of intervals, and Python's default recursion limit of about 1000 frames can be exceeded.
A Generator Version
If the caller wants to stop after a few results, collecting everything first wastes work. A generator reports intervals lazily, and the pruning is the same.
def iter_overlaps(node, lo, hi):
# Yields every stored interval overlapping [lo, hi], in order of low endpoint.
if node is None or node.max < lo:
return
yield from iter_overlaps(node.left, lo, hi)
if node.lo <= hi and lo <= node.hi:
yield (node.lo, node.hi)
if node.lo <= hi:
yield from iter_overlaps(node.right, lo, hi)
# Reusing root from the previous example:
first_two = []
for interval in iter_overlaps(root, 14, 16):
first_two.append(interval)
if len(first_two) == 2:
break
print(first_two) # [(5, 20), (10, 30)]Stopping after two results leaves the rest of the tree unvisited. Every yield from level adds a small cost, so for large result sets the list-based version is slightly faster.
How Much Work Does It Do?
Let n be the number of stored intervals, h the tree height, and k the number of reported intervals. A standard analysis bounds the work by O(min(n, k log n)) on a balanced tree. The search does one root-to-leaf style descent even when k is zero, which is the log n part. Each reported interval can cost an extra path of at most h nodes. When k approaches n, the cost cannot exceed visiting every node, which gives the n term.
This is different from find_overlap, which is O(h) no matter how many overlaps exist. The tree gives you two tools, and you should pick by what the caller needs.
| Question | Function | Cost on a balanced tree |
|---|---|---|
| Is there any overlap? | `find_overlap` | O(log n) |
| What are all overlaps? | `find_all` | O(min(n, k log n)) |
Output size matters as well. Any algorithm that reports k intervals needs at least O(k) time to write them down, so the k factor cannot be avoided.
Exercises
Exercise
On the example tree, find_all is called with the query [30, 35]. Which stored intervals are reported, and is the node (5, 20) visited?
Show answer
The reported intervals are (10, 30), (30, 40). The root (15, 20) has max 40, so the search continues. At (10, 30), max is 30 and 30 >= 30, so the search continues, which shows why the prune must be strict. The node (10, 30) overlaps because 30 <= 30 touches the query's low end. Its left child (5, 20) is entered, because the check on it is its own max: 20 < 30, so it returns immediately. It is visited as a call but does no work. The root does not overlap (20 < 30). Its right child (17, 19) has max 40, so the search enters it. It does not overlap, but 17 <= 35 so its right child (30, 40) is entered and reported.
Exercise
Why can find_all not choose a single child to descend into, as find_overlap does?
Show answer
Both subtrees can contain overlapping intervals at once, and every one of them must be reported. find_overlap may stop at the first overlap it finds. find_all may skip a subtree only when it has proof that the subtree holds no overlap, which the max test (node.max < lo) and the low-endpoint test (node.lo > hi) provide.