Sub topic 17
Where Interval Trees Are Used
This chapter shows which real problems call for an interval tree and which don't. It assumes you know the closed-interval overlap test, the max-endpoint invariant, and the insertion and search code from earlier chapters. The examples reuse that code.
What a Good Fit Looks Like
An interval tree pays off when three conditions hold together:
- The data are ranges, such as time spans, address ranges, or positions on a sequence.
- The set changes over time, with inserts and deletes mixed in with queries.
- You repeatedly ask "what overlaps this range?" or "what covers this point?"
If any condition is missing, a simpler tool may do better. Static data can be sorted once. A set that is queried only once can be scanned once. The sections below show where all three conditions hold.
Scheduling and Conflict Detection
Calendars, room booking, and resource allocation all ask one question before accepting a new item: does it collide with anything already booked? With n bookings, a linear scan costs O(n) per request. An interval tree answers in O(log n) and also accepts the new booking in O(log n).
The example below uses minutes since midnight. Meetings are normally half-open: a meeting from 9:00 to 10:00 does not conflict with one starting at 10:00. Our tree stores closed intervals, so the code converts each meeting [start, end) to the closed interval [start, end - 1].
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
def try_book(root, start, end):
# start is inclusive, end is exclusive, both in minutes
lo, hi = start, end - 1
clash = find_overlap(root, lo, hi)
if clash is not None:
return root, (clash[0], clash[1] + 1)
return insert(root, lo, hi), None
root = None
for start, end in [(540, 600), (600, 660), (630, 690)]:
root, clash = try_book(root, start, end)
print((start, end), "clash with", clash)The output is:
(540, 600) clash with None
(600, 660) clash with None
(630, 690) clash with (600, 660)The second meeting starts exactly when the first ends and is accepted. The third starts inside the second and is rejected. Only find_overlap is needed here, because a booking system just needs to know whether any conflict exists. Showing the user every conflict would use find_all instead.
Genomics and Annotation Lookup
A genome is a long coordinate line. Genes, exons, regulatory regions, and sequencing reads are all intervals on it. A common task is to take a set of reads, or variants, and find which annotated features each one overlaps. The annotation set can hold millions of intervals, and the query set can be even larger.
Two details of this workload matter:
- A point lookup, such as "which features contain position 1,204,331?", is a stabbing query. You run it as an overlap query with
lo == hi. - Queries often return many hits, because genes overlap and exons nest inside them. Use the report-all search, whose cost grows with the number of results (roughly O(k log n) for k hits), not the single-result search.
Bioinformatics libraries index intervals in several ways. Some use interval trees, some use sorted arrays with binning, and some use nested containment lists. Python packages such as intervaltree expose the tree directly. Which index a given tool uses is an implementation choice, so check its documentation before assuming.
Geometry, Graphics, and Windowing
Overlap on a line is the one-dimensional version of several geometric problems.
- Rectangle intersection. Two axis-aligned rectangles overlap exactly when their x-intervals overlap and their y-intervals overlap. A sweep line moving across x keeps the active rectangles' y-intervals in an interval tree. Each new rectangle is checked against the tree.
- Visibility and layout. Text layout, timeline views, and Gantt charts need to know which items occupy the same row at the same moment. Overlap queries on the time axis answer this.
- Collision broad phase. Some engines project objects onto an axis and look for overlapping projections before running exact tests. An interval tree can serve as the index when objects move and the set changes.
Systems Software, Networks, and Databases
Operating systems and databases hold many range-valued records.
- Memory and file ranges. The Linux kernel contains a generic interval tree built on a red-black tree. It is used to find which mappings cover a given range of pages. This is a balanced augmented BST of the kind from the balancing chapter, with the max value maintained through rotations.
- IP address ranges. A firewall or geolocation table maps address ranges to rules or regions. A lookup is a stabbing query on one address. If the ranges never overlap, a sorted array and binary search is simpler. If rules can overlap and you need all matching ones, an interval tree handles it.
- Temporal databases. Rows carry a validity period
[valid_from, valid_to]. "Which rows were valid at time t?" is a stabbing query. "Which rows were valid at any point in this quarter?" is an overlap query. Database engines usually reach for B-tree or GiST-style indexes here, but the underlying question is the same.
When Another Structure Is Better
The table lists common situations and a reasonable first choice.
| Situation | Better choice | Reason |
|---|---|---|
| Data never change after loading | Sorted arrays, or a static tree built once | No need to pay for insert and delete support |
| Intervals never overlap each other | Sorted list plus binary search | At most one interval covers a point |
| Mostly point queries, fixed set of coordinates | Segment tree | Handles stabbing and aggregation over a known coordinate range |
| Heavy stabbing queries, static set | Centered interval tree | Simple layout, fast stabbing |
| Dynamic set, overlap and stabbing queries | Balanced augmented BST | Supports inserts, deletes, and both query types |
| Fewer than a few hundred intervals | Linear scan | Constant factors beat log n |
The last row deserves attention. A tree has pointer-chasing overhead, and a loop over a short list is often faster in practice. Measure with your own data before adopting the tree.
Common Pitfalls in Practice
- Open versus closed ends. Real data such as meetings, byte ranges, and genome coordinates often use half-open ranges. Convert them at the boundary, as
try_bookdoes, or you will report false conflicts for ranges that merely touch. Some genome formats are zero-based and half-open, while others are one-based and closed, so check which one your data uses. - Unbalanced input. The tree from the insertion chapter does not rebalance. Inserting intervals sorted by low endpoint, which is common with log data, produces a chain of height n. Use a balanced version for real workloads.
- Duplicate intervals. Our
insertsends equal low endpoints to the right. Decide whether duplicates are allowed. A booking system may want to reject them. An annotation index must keep them. - Output size. Report-all cost grows with the number of hits. A query that covers the whole range returns all n intervals, so no structure can make it fast.
- Mutating stored intervals. Changing an interval's endpoints in place invalidates the
maxfields above it. Delete the interval and insert the updated one.
Exercise
A ticketing system stores seat holds as time intervals [hold_start, hold_end) in whole seconds. A new hold request for [1000, 1060) arrives. Which closed interval do you search for in the tree, and why would searching for (1000, 1060) as a closed interval cause a bug?
Show answer
Search for the closed interval (1000, 1059), because the half-open end 1060 is not part of the hold. Searching (1000, 1060) would treat a stored hold that starts at exactly second 1060 as a conflict, since closed intervals sharing an endpoint overlap. That rejects a valid back-to-back booking.
Exercise
You need to index 5 million non-overlapping IP ranges that are loaded once and queried millions of times for a single address. Would you build an augmented interval tree? Explain your choice.
Show answer
No. The data are static and non-overlapping, so a sorted array of ranges with binary search finds the one covering range in O(log n) with less memory and better cache behavior. The tree's support for inserts, deletes, and overlapping ranges is not needed.