Lesson 9 · Advanced structures and algorithms

Interval Trees

A binary search tree of intervals ordered by start point, where every node also remembers the latest end point in its subtree. That one number turns "does anything overlap this?" into a single root-to-leaf walk.

Interval Trees concept diagramA query interval shown as a shaded band, with six intervals beside it: one ending before it, four overlapping it in different ways, and one starting after it.query qends before q✗high < q.lowoverlaps q's start✓inside q✓contains q✓overlaps q's end✓starts after q✗low > q.highoverlap ⇔ low ≤ q.high and q.low ≤ highonly two ways to miss — the tree's max field rules out the first for a whole subtree at once
1

Intervals Keyed by Their Start

  1. Stores – intervals [low, high], such as meetings, memory ranges or genome segments.
  2. Key – each node is placed in a binary search tree by its interval's low end.
  3. Augmented field – max: the largest high end among the node and all its descendants.
  4. Main query – find an interval that overlaps a query interval, or report all of them.
  5. Balance – built on a red-black or AVL tree so the height stays O(log n).

An interval tree is a data structure for a set of intervals that answers the question "which stored intervals overlap this one?" quickly. A plain list has to test every interval, O(n) per query. This tree finds one overlap in O(log n), and reports all k of them with at most one short path per answer.

The version taught in CLRS, and used here, is an augmented binary search tree. It is an ordinary balanced BST keyed on the low endpoints, with one extra number per node. That extra number — the maximum high endpoint anywhere in the subtree — is what lets the search discard half the tree at each step.

  • Also called an interval search tree
  • Equal low ends: break ties by the high end so every key is distinct
2

When Do Two Intervals Overlap?

Closed intervals a = [a.low, a.high] and b = [b.low, b.high] overlap exactly when a.low ≤ b.high and b.low ≤ a.high — each one starts before the other ends. The easiest way to remember it is by the two ways to miss: a ends before b starts (a.high < b.low), or a starts after b ends (a.low > b.high). Negate both and you get the test.

The diagram above shows the six cases. The four overlap cases look very different — partial on either side, one inside the other — but a single two-comparison test covers all of them. For half-open intervals such as time slots [start, end), replace ≤ with <, so that meetings 9–10 and 10–11 do not count as overlapping.

  • Touching closed intervals such as [1, 3] and [3, 5] overlap; touching half-open ones do not
  • A point query x is just the interval [x, x]
  • Reject reversed intervals (low > high) on insert; the test assumes low ≤ high
3

Insert and Search

  1. Insert – walk down by low endpoint as in any BST; on the way, set each ancestor's max = max(max, high); attach the new node as a leaf with max = high.
  2. Search, step 1 – if the current node overlaps the query, return it.
  3. Search, step 2 – if the left child exists and left.max ≥ query.low, go left.
  4. Search, step 3 – otherwise go right.
  5. Search, step 4 – reaching null means no interval overlaps the query.

Why is going left safe? If left.max ≥ query.low, some interval on the left ends at or after the query starts. Either it overlaps the query — then the left side has an answer — or it starts after the query ends. In that second case every interval on the right starts even later (the BST orders by low), so nothing on the right can overlap either. Either way, the left subtree is the only place worth looking.

If left.max < query.low, every interval on the left ends before the query starts, so none of them can overlap, and the search goes right. Each step discards one whole subtree, so a search follows one root-to-leaf path.

Rotations used for balancing only need to recompute max for the two nodes they move, from their children: max = max(high, left.max, right.max). That keeps insert and delete at O(log n).

  • Search returns some overlapping interval, not necessarily the one that starts first
  • Delete must recompute max on every node of the path back to the root
Key reference

Terms, operations, and practical uses

Terms to know

  • Augmented treeA tree whose nodes carry extra data computed from their subtree, kept correct on every update.
  • max fieldThe largest high endpoint in a node's subtree.
  • Overlapa.low ≤ b.high and b.low ≤ a.high.
  • Output-sensitiveA cost that grows with the size of the answer k, such as O(k log n).
Implementation

Code in Python, C++ and Java

class Node:
    def __init__(self, low, high):
        self.low, self.high = low, high
        self.max = high  # largest high endpoint anywhere in this subtree
        self.left = self.right = None


def insert(node, low, high):
    if node is None:
        return Node(low, high)
    if low < node.low:
        node.left = insert(node.left, low, high)
    else:
        node.right = insert(node.right, low, high)
    node.max = max(node.max, high)
    return node


def overlaps(node, low, high):
    return node.low <= high and low <= node.high


def search_any(node, low, high):
    while node is not None and not overlaps(node, low, high):
        # If anything on the left ends at or after low, an overlap (if one
        # exists at all) can be found there; otherwise only the right can help.
        if node.left is not None and node.left.max >= low:
            node = node.left
        else:
            node = node.right
    return node


def search_all(node, low, high, found):
    if node is None or node.max < low:
        return  # nothing in this subtree ends late enough
    search_all(node.left, low, high, found)
    if overlaps(node, low, high):
        found.append([node.low, node.high])
    if node.low <= high:  # right subtree starts at node.low or later
        search_all(node.right, low, high, found)


root = None
for low, high in [(15, 20), (10, 30), (17, 19), (5, 20), (12, 15), (30, 40)]:
    root = insert(root, low, high)

for query in [(6, 7), (41, 45)]:
    hit = search_any(root, *query)
    print(f"any overlap with {list(query)}:", [hit.low, hit.high] if hit else "none")

found = []
search_all(root, 14, 16, found)
print("all overlaps with [14, 16]:", *found)
#include <algorithm>
#include <iostream>
#include <memory>
#include <vector>
using namespace std;

struct Node {
    int low, high;
    int max;  // largest high endpoint anywhere in this subtree
    unique_ptr<Node> left, right;
    Node(int lo, int hi) : low(lo), high(hi), max(hi) {}
};

void insert(unique_ptr<Node>& node, int low, int high) {
    if (!node) {
        node = make_unique<Node>(low, high);
        return;
    }
    if (low < node->low) {
        insert(node->left, low, high);
    } else {
        insert(node->right, low, high);
    }
    node->max = max(node->max, high);
}

bool overlaps(const Node* node, int low, int high) {
    return node->low <= high && low <= node->high;
}

const Node* searchAny(const Node* node, int low, int high) {
    while (node && !overlaps(node, low, high)) {
        // If anything on the left ends at or after low, an overlap (if one
        // exists at all) can be found there; otherwise only the right can help.
        if (node->left && node->left->max >= low) {
            node = node->left.get();
        } else {
            node = node->right.get();
        }
    }
    return node;
}

void searchAll(const Node* node, int low, int high, vector<const Node*>& found) {
    if (!node || node->max < low) return;  // nothing here ends late enough
    searchAll(node->left.get(), low, high, found);
    if (overlaps(node, low, high)) found.push_back(node);
    if (node->low <= high) searchAll(node->right.get(), low, high, found);
}

int main() {
    unique_ptr<Node> root;
    int intervals[][2] = {{15, 20}, {10, 30}, {17, 19}, {5, 20}, {12, 15}, {30, 40}};
    for (auto& iv : intervals) insert(root, iv[0], iv[1]);

    int queries[][2] = {{6, 7}, {41, 45}};
    for (auto& q : queries) {
        const Node* hit = searchAny(root.get(), q[0], q[1]);
        cout << "any overlap with [" << q[0] << ", " << q[1] << "]: ";
        if (hit) {
            cout << "[" << hit->low << ", " << hit->high << "]\n";
        } else {
            cout << "none\n";
        }
    }

    vector<const Node*> found;
    searchAll(root.get(), 14, 16, found);
    cout << "all overlaps with [14, 16]:";
    for (const Node* n : found) cout << " [" << n->low << ", " << n->high << "]";
    cout << "\n";
    return 0;
}
import java.util.ArrayList;
import java.util.List;

public class Main {
    static class Node {
        final int low, high;
        int max; // largest high endpoint anywhere in this subtree
        Node left, right;

        Node(int low, int high) {
            this.low = low;
            this.high = high;
            this.max = high;
        }
    }

    static Node insert(Node node, int low, int high) {
        if (node == null) return new Node(low, high);
        if (low < node.low) {
            node.left = insert(node.left, low, high);
        } else {
            node.right = insert(node.right, low, high);
        }
        node.max = Math.max(node.max, high);
        return node;
    }

    static boolean overlaps(Node node, int low, int high) {
        return node.low <= high && low <= node.high;
    }

    static Node searchAny(Node node, int low, int high) {
        while (node != null && !overlaps(node, low, high)) {
            // If anything on the left ends at or after low, an overlap (if one
            // exists at all) can be found there; otherwise only the right can help.
            node = (node.left != null && node.left.max >= low) ? node.left : node.right;
        }
        return node;
    }

    static void searchAll(Node node, int low, int high, List<String> found) {
        if (node == null || node.max < low) return; // nothing here ends late enough
        searchAll(node.left, low, high, found);
        if (overlaps(node, low, high)) found.add("[" + node.low + ", " + node.high + "]");
        if (node.low <= high) searchAll(node.right, low, high, found);
    }

    public static void main(String[] args) {
        Node root = null;
        int[][] intervals = {{15, 20}, {10, 30}, {17, 19}, {5, 20}, {12, 15}, {30, 40}};
        for (int[] iv : intervals) root = insert(root, iv[0], iv[1]);

        int[][] queries = {{6, 7}, {41, 45}};
        for (int[] q : queries) {
            Node hit = searchAny(root, q[0], q[1]);
            String text = hit == null ? "none" : "[" + hit.low + ", " + hit.high + "]";
            System.out.println("any overlap with [" + q[0] + ", " + q[1] + "]: " + text);
        }

        List<String> found = new ArrayList<>();
        searchAll(root, 14, 16, found);
        System.out.println("all overlaps with [14, 16]: " + String.join(" ", found));
    }
}
Watch it run

Step through it

Running on [15,20] [10,30] [17,19] [5,20] [12,15] [30,40]; queries [6,7], [41,45], all of [14,16]

[15,20][10,30][17,19][5,20][12,15][30,40]01020304045key = low end; extra field = max high end below
Step 1

Six intervals to store

An interval tree is a binary search tree ordered by each interval's low end. Every node also stores max: the largest high end in its subtree. That one extra number is what lets a search skip whole subtrees.

Output
1 / 17
4

Finding All Overlapping Intervals

Reporting every overlap needs both subtrees, but the same fields still prune. Skip a subtree entirely when its max < query.low — everything in it ends too early. Skip a node's right subtree when the node's low > query.high — everything there starts too late. Everything else is visited, in order.

In a balanced tree each reported interval costs at most one root-to-leaf path, so the query is O(min(n, k log n)) for k answers (the CLRS bound), and close to O(log n + k) when the answers sit together. A different design, the centred interval tree, guarantees O(log n + k). For the meeting-room style question "which bookings clash with 14:00–16:00?" this is the query that matters.

  • Visiting nodes in order returns the overlaps sorted by start
  • For one batch of queries on a fixed set, sorting and sweeping can be simpler than a tree
5

Costs, and When a Segment Tree Fits Better

The bounds assume the underlying BST is balanced. Built from sorted input without balancing, the tree becomes a chain and every operation degrades to O(n) — the same problem as an unbalanced binary search tree.

Interval tree vs segment tree
Interval treeSegment tree
StoresA dynamic set of intervalsValues over a fixed array of positions
QuestionWhich intervals overlap this one?Aggregate (sum, min) over a range of positions
UpdatesInsert and delete intervalsChange values at positions
SpaceO(n)O(n) for the array; O(n log n) for the interval-stabbing variant
  • Insert and delete: O(log n), a BST update plus max fixes on one path
  • Find one overlap: O(log n), one root-to-leaf path
  • Find all k overlaps: O(min(n, k log n))
  • Space: O(n), one node and one extra number per interval