TExcelTAD

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 ii" in O(lg⁡n)O(\lg n) 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 [a,b][a, b] with a≤ba \le b is the set of reals xx with a≤x≤ba \le x \le b; write i.low=ai.\textit{low} = a and i.high=bi.\textit{high} = b. Two intervals ii and jj overlap exactly when

i.low≤j.highandj.low≤i.highi.\textit{low} \le j.\textit{high} \quad \text{and} \quad j.\textit{low} \le i.\textit{high}

Otherwise one lies entirely to the left of the other: i.high<j.lowi.\textit{high} < j.\textit{low} or j.high<i.lowj.\textit{high} < i.\textit{low}. 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.

python · try it yourself
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

  1. Underlying structure: a red-black tree in which each node xx holds an interval x.intx.\textit{int}, keyed by its low endpoint, so an inorder walk lists the intervals by low endpoint.
  2. Extra information: x.maxx.\textit{max}, the largest high endpoint of any interval in the subtree of xx.
  3. Maintenance: x.max=max⁡(x.int.high, x.left.max, x.right.max)x.\textit{max} = \max(x.\textit{int}.\textit{high},\ x.\textit{left}.\textit{max},\ x.\textit{right}.\textit{max}), computed from xx and its children, so by the augmentation theorem insertion and deletion stay O(lg⁡n)O(\lg n) (the sentinel's max is −∞-\infty).
  4. New operation: INTERVAL-SEARCH.
text
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 x

One downward path, O(lg⁡n)O(\lg n) 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 ii if one exists.

Proof. We show the invariant: if the tree contains an interval overlapping ii, then the subtree of xx contains one. It holds at the root. Consider one iteration.

  • Going right (line 5). Either the left subtree is empty, or x.left.max<i.lowx.\textit{left}.\textit{max} < i.\textit{low}: every interval on the left ends before ii starts, so none of them overlaps ii. Any overlapping interval in xx's subtree must be in the right subtree.
  • Going left (line 4). Here x.left.max≥i.lowx.\textit{left}.\textit{max} \ge i.\textit{low}, so some interval jj in the left subtree has j.high=x.left.max≥i.lowj.\textit{high} = x.\textit{left}.\textit{max} \ge i.\textit{low}. If jj overlaps ii, the left subtree has an overlap. If not, then jj lies entirely to the right of ii: i.high<j.lowi.\textit{high} < j.\textit{low}. Every interval j′j' in the right subtree has a low endpoint at least j.lowj.\textit{low} (the tree is keyed by low endpoints), so i.high<j.low≤j′.lowi.\textit{high} < j.\textit{low} \le j'.\textit{low} and no interval on the right overlaps ii either. So if any overlap exists in xx's subtree, it is on the left.

When the loop stops, either xx overlaps ii or xx 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.

python · try it yourself
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: [19,19][19, 19] falls into the gap between [12,18][12, 18] and [20,27][20, 27]. At [30,34][30, 34] 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 [36,36][36, 36] on the right. By the theorem, an interval on the right would start after [24,25][24, 25] 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).

cpp · try it yourself
#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 ii, 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 most i.high). Reporting kk intervals costs O(min⁡(n,klg⁡n))O(\min(n, k \lg n)) 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 2n2n endpoints and sweep, counting +1+1 at each start and −1-1 at each end. That is the practice problem Maximum Overlap of Intervals, whose intervals are half-open [a,b)[a, b), so an end at xx must be processed before a start at xx. 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 [3,7][3, 7] and [7,10][7, 10] overlap (closed intervals)?

  1. yes: they share the point 7
  2. no: they only touch
  3. only if the tree is keyed by high endpoints
  4. it depends on the order of insertion

What does x.maxx.max store in an interval tree?

  1. the largest low endpoint in xx's subtree
  2. the largest high endpoint of any interval in xx's subtree
  3. the length of the longest interval
  4. the number of intervals in the subtree

INTERVAL-SEARCH goes left at xx and finds no overlap in the left subtree. Why can it skip the right subtree?

  1. Because the right subtree is always empty
  2. Because some left interval jj has j.high≥i.lowj.high \ge i.low but does not overlap ii, so i.high<j.lowi.high < j.low, and every right interval starts at or after j.lowj.low
  3. Because xx overlaps ii
  4. It cannot; this is a bug