Interval Trees
Many questions are about intervals rather than single keys: which meetings overlap 14:00 to 15:00, which genes overlap a region of a chromosome, which rectangles might intersect a new one (one dimension at a time). An interval tree stores a dynamic set of intervals and answers "give me a stored interval that overlaps " in time. It is the second classic application of the augmentation method, and its search procedure is a nice example of a correctness proof that is not obvious at all.
Intervals and overlap
A closed interval with is the set of reals with ; write and . Two intervals and overlap exactly when
Otherwise one lies entirely to the left of the other: or . This trichotomy is all the proofs below use.
The program checks the trichotomy exhaustively for all pairs of integer intervals with endpoints from 0 to 7: every pair either overlaps or has one interval entirely to the left of the other, never both and never neither.
from itertools import combinations_with_replacement, product
def overlaps(i, j):
return i[0] <= j[1] and j[0] <= i[1]
ivs = [(a, b) for a, b in combinations_with_replacement(range(8), 2)] # all [a, b] with a <= b
counts = {"overlap": 0, "i left of j": 0, "j left of i": 0}
for i, j in product(ivs, repeat=2):
cases = [overlaps(i, j), i[1] < j[0], j[1] < i[0]]
assert sum(cases) == 1 # exactly one of the three
counts[["overlap", "i left of j", "j left of i"][cases.index(True)]] += 1
print(len(ivs), "intervals,", len(ivs) ** 2, "ordered pairs:", counts)
print("[3, 7] and [7, 10] overlap:", overlaps((3, 7), (7, 10)), "| [3, 6] and [7, 10]:", overlaps((3, 6), (7, 10)))36 intervals, 1296 ordered pairs: {'overlap': 876, 'i left of j': 210, 'j left of i': 210}
[3, 7] and [7, 10] overlap: True | [3, 6] and [7, 10]: False
The augmentation, in four steps
- Underlying structure: a red-black tree in which each node holds an interval , keyed by its low endpoint, so an inorder walk lists the intervals by low endpoint.
- Extra information: , the largest high endpoint of any interval in the subtree of .
- Maintenance: , computed from and its children, so by the augmentation theorem insertion and deletion stay (the sentinel's max is ).
- New operation: INTERVAL-SEARCH.
INTERVAL-SEARCH(T, i) // a node whose interval overlaps i, or T.nil
1 x = T.root
2 while x != T.nil and i does not overlap x.int
3 if x.left != T.nil and x.left.max >= i.low
4 x = x.left // an overlap, if any exists, is on the left
5 else x = x.right // no overlap on the left: only the right can have one
6 return xOne downward path, time.
Why one path is enough
The surprising part is line 4: after going left, the search never comes back, even if the left subtree turns out to contain no overlap. The theorem says that is safe.
Theorem. INTERVAL-SEARCH returns a node overlapping if one exists.
Proof. We show the invariant: if the tree contains an interval overlapping , then the subtree of contains one. It holds at the root. Consider one iteration.
- Going right (line 5). Either the left subtree is empty, or : every interval on the left ends before starts, so none of them overlaps . Any overlapping interval in 's subtree must be in the right subtree.
- Going left (line 4). Here , so some interval in the left subtree has . If overlaps , the left subtree has an overlap. If not, then lies entirely to the right of : . Every interval in the right subtree has a low endpoint at least (the tree is keyed by low endpoints), so and no interval on the right overlaps either. So if any overlap exists in 's subtree, it is on the left.
When the loop stops, either overlaps or is the sentinel; by the invariant, the sentinel means there was no overlap anywhere.
An implementation
The tree below is the augmented red-black insertion from the previous lesson with max as its only field. The program stores a small set of intervals, prints the path taken by three searches, and then checks the search against brute force on many random instances, including the claim that it never misses.
import random
RED, BLACK = "R", "B"
class Node:
__slots__ = ("low", "high", "max", "color", "left", "right", "parent")
def __init__(self, low, high, color, nil):
self.low, self.high, self.color = low, high, color
self.max = high if low is not None else float("-inf")
self.left = self.right = self.parent = nil
class IntervalTree:
def __init__(self):
self.nil = Node(None, None, BLACK, None)
self.root = self.nil
def pull(self, x):
x.max = max(x.high, x.left.max, x.right.max)
def rotate(self, x, d):
nil, o = self.nil, ("right" if d == "left" else "left")
y = getattr(x, o)
setattr(x, o, getattr(y, d))
if getattr(y, d) is not nil: getattr(y, d).parent = x
y.parent = x.parent
if x.parent is nil: self.root = y
elif x is x.parent.left: x.parent.left = y
else: x.parent.right = y
setattr(y, d, x)
x.parent = y
self.pull(x); self.pull(y)
def insert(self, low, high):
z, y, x = Node(low, high, RED, self.nil), self.nil, self.root
while x is not self.nil:
y, x = x, (x.left if low < x.low else x.right)
z.parent = y
if y is self.nil: self.root = z
elif low < y.low: y.left = z
else: y.right = z
a = y
while a is not self.nil:
self.pull(a); a = a.parent
while z.parent.color == RED:
p = z.parent; g = p.parent
a, b = ("left", "right") if p is g.left else ("right", "left")
u = getattr(g, b)
if u.color == RED:
p.color = u.color = BLACK; g.color = RED; z = g; continue
if z is getattr(p, b):
z = p; self.rotate(z, a); p = z.parent
p.color = BLACK; g.color = RED; self.rotate(g, b)
self.root.color = BLACK
def search(self, low, high, trace=None):
x = self.root
while x is not self.nil and not (x.low <= high and low <= x.high):
if x.left is not self.nil and x.left.max >= low:
if trace is not None: trace.append(f"[{x.low},{x.high}] no; left max {x.left.max} >= {low}: go left")
x = x.left
else:
if trace is not None: trace.append(f"[{x.low},{x.high}] no; go right")
x = x.right
return None if x is self.nil else (x.low, x.high)
t = IntervalTree()
for iv in [(12, 18), (3, 6), (30, 34), (7, 9), (20, 27), (14, 15), (36, 36), (1, 2), (10, 11), (24, 25)]:
t.insert(*iv)
for q in [(28, 29), (19, 19), (8, 8)]:
trace = []
found = t.search(*q, trace)
print(f"search {list(q)}: {'; '.join(trace) or 'root overlaps'} -> {found}")
rng = random.Random(17)
misses = 0
for trial in range(300):
t, ivs = IntervalTree(), []
for _ in range(rng.randint(1, 40)):
a = rng.randrange(100); b = a + rng.randrange(15)
t.insert(a, b); ivs.append((a, b))
for _ in range(20):
a = rng.randrange(110); b = a + rng.randrange(10)
found = t.search(a, b)
exists = any(lo <= b and a <= hi for lo, hi in ivs)
assert (found is not None) == exists
assert found is None or (found[0] <= b and a <= found[1])
print("6000 random queries: the search finds an overlap exactly when one exists")search [28, 29]: [12,18] no; go right; [20,27] no; go right; [30,34] no; go right; [36,36] no; go right -> None
search [19, 19]: [12,18] no; go right; [20,27] no; go right; [30,34] no; left max 25 >= 19: go left; [24,25] no; go right -> None
search [8, 8]: [12,18] no; left max 11 >= 8: go left; [3,6] no; go right -> (7, 9)
6000 random queries: the search finds an overlap exactly when one exists
Look at the second search: falls into the gap between and . At the search goes left, because the left subtree's maximum 25 reaches past 19; it finds no overlap there and correctly reports none, without ever visiting on the right. By the theorem, an interval on the right would start after starts, which is already after the query ends.
In C++
The same tree in C++, tested on 100,000 random queries against brute force over 2000 intervals (a fixed seed, so the counts are reproducible).
#include <algorithm>
#include <climits>
#include <cstdio>
#include <random>
#include <vector>
class IntervalTree {
struct Node { int low = 0, high = 0, max = INT_MIN; bool red = false; int left = 0, right = 0, parent = 0; };
std::vector<Node> t{Node{}}; // t[0]: sentinel with max = -infinity
int root = 0;
int& child(int x, bool right) { return right ? t[x].right : t[x].left; }
void pull(int x) { t[x].max = std::max({t[x].high, t[t[x].left].max, t[t[x].right].max}); }
void rotate(int x, bool left) {
int y = child(x, left);
child(x, left) = child(y, !left);
if (child(y, !left) != 0) t[child(y, !left)].parent = x;
t[y].parent = t[x].parent;
if (t[x].parent == 0) root = y;
else if (x == t[t[x].parent].left) t[t[x].parent].left = y;
else t[t[x].parent].right = y;
child(y, !left) = x;
t[x].parent = y;
pull(x); pull(y);
}
public:
void insert(int low, int high) {
int y = 0, x = root;
while (x != 0) { y = x; x = low < t[x].low ? t[x].left : t[x].right; }
t.push_back({low, high, high, true, 0, 0, y});
int z = static_cast<int>(t.size()) - 1;
if (y == 0) root = z; else if (low < t[y].low) t[y].left = z; else t[y].right = z;
for (int a = y; a != 0; a = t[a].parent) pull(a);
while (t[t[z].parent].red) {
int p = t[z].parent, g = t[p].parent;
bool left = p == t[g].left;
int u = child(g, left);
if (t[u].red) { t[p].red = t[u].red = false; t[g].red = true; z = g; continue; }
if (z == child(p, left)) { z = p; rotate(z, left); p = t[z].parent; }
t[p].red = false; t[g].red = true;
rotate(g, !left);
}
t[root].red = false;
}
bool search(int low, int high, int& steps) const {
int x = root;
steps = 0;
while (x != 0 && !(t[x].low <= high && low <= t[x].high)) {
++steps;
x = (t[x].left != 0 && t[t[x].left].max >= low) ? t[x].left : t[x].right;
}
return x != 0;
}
};
int main() {
std::mt19937 rng(17);
IntervalTree tree;
std::vector<std::pair<int, int>> ivs;
for (int i = 0; i < 2000; ++i) {
int a = static_cast<int>(rng() % 1000000), b = a + static_cast<int>(rng() % 200);
tree.insert(a, b); ivs.push_back({a, b});
}
int found = 0, wrong = 0, worst = 0;
for (int q = 0; q < 100000; ++q) {
int a = static_cast<int>(rng() % 1000000), b = a + static_cast<int>(rng() % 100), steps;
bool hit = tree.search(a, b, steps);
bool exists = std::any_of(ivs.begin(), ivs.end(), [&](auto& iv) { return iv.first <= b && a <= iv.second; });
wrong += hit != exists;
found += hit;
worst = std::max(worst, steps);
}
std::printf("100000 queries: %d found an overlap, %d wrong answers, longest search path %d steps\n", found, wrong, worst);
}100000 queries: 25709 found an overlap, 0 wrong answers, longest search path 13 steps
Beyond one answer
- All overlaps. To list every stored interval overlapping , search both subtrees whenever they might contain one (go left if
left.max >= i.low, go right if the node's low endpoint is at mosti.high). Reporting intervals costs this way; specialised structures do better. - Maximum overlap. "What is the largest number of intervals sharing a point?" needs no tree when the intervals are known in advance: sort the endpoints and sweep, counting at each start and at each end. That is the practice problem Maximum Overlap of Intervals, whose intervals are half-open , so an end at must be processed before a start at . With insertions and deletions mixed in, the same question is answered by augmenting a tree on the endpoints with prefix-sum maxima, another application of the augmentation theorem.
Test yourself
Do and overlap (closed intervals)?
- yes: they share the point 7
- no: they only touch
- only if the tree is keyed by high endpoints
- it depends on the order of insertion
What does store in an interval tree?
- the largest low endpoint in 's subtree
- the largest high endpoint of any interval in 's subtree
- the length of the longest interval
- the number of intervals in the subtree
INTERVAL-SEARCH goes left at and finds no overlap in the left subtree. Why can it skip the right subtree?
- Because the right subtree is always empty
- Because some left interval has but does not overlap , so , and every right interval starts at or after
- Because overlaps
- It cannot; this is a bug