Sub topic 16
Interval Trees Versus Segment Trees and Other Structures
This chapter assumes you have read the earlier chapters. You should know the closed-interval overlap test, the augmented binary search tree (BST) with a max-endpoint field, and the cost of finding one overlap versus reporting all overlaps. Here we compare that design with its neighbors so you can pick one for a real problem.
What You Are Choosing Between
The augmented BST from this tutorial is usually just called an interval tree. Four other designs solve similar problems:
- Centered interval tree. Each node holds a center point and the intervals that cross it. Left and right children hold intervals entirely below or above the center.
- Segment tree. It splits a fixed coordinate range into elementary pieces. Each interval is stored in the O(log n) nodes that together cover it.
- Sorted arrays and sweep lines. These suit static data or batch problems.
- Priority search trees and R-trees. These are used for related queries, such as three-sided range queries or multidimensional boxes.
Take n as the number of stored intervals and k as the number of results a query reports.
Side-by-Side Comparison
| Structure | Space | Build | Insert / delete | Find one overlap | Report all overlaps |
|---|---|---|---|---|---|
| Augmented BST (balanced) | O(n) | O(n log n) | O(log n) | O(log n) | O(k log n), pruned search |
| Centered interval tree | O(n) | O(n log n) | Hard, usually rebuild | not a separate case | O(log n + k) |
| Segment tree | O(n log n) | O(n log n) | Only for known coordinates | not a separate case | O(log n + k) for stabbing |
| Sorted array + prefix max | O(n) | O(n log n) | O(n) | O(log n) | needs extra work |
Read the table with these points in mind:
- The augmented BST is the only structure here with simple, worst-case O(log n) updates and O(n) space. That is why it is the default for dynamic sets.
- The O(k log n) bound for reporting all overlaps is a safe upper bound for the simple pruned traversal from the earlier chapter. It is not always tight. A well-implemented traversal can do better on many inputs, but the guarantee is weaker than the O(log n + k) of the other two trees.
- The centered tree and segment tree have output-sensitive bounds. The log factor is paid once, and each result costs O(1) extra.
- A "static" cell does not mean the structure is bad. Many workloads load data once and query millions of times.
Centered Interval Tree in Practice
A centered tree picks a center, usually the median of all endpoints. Intervals that contain the center stay at the node. They are kept in two sorted lists, one by low endpoint and one by high endpoint. A query point left of the center scans the low-sorted list from the smallest value and stops at the first low endpoint above the point. That scan finds every hit and no misses, so the cost is proportional to the output. The query then recurses into the left child only.
The weakness is mutation. Inserting an interval that crosses no existing center may require new nodes. Deleting can empty a node. Keeping the tree balanced under updates is awkward. Libraries that use centered trees often treat the set as mostly read-only and rebuild when it changes.
Segment Trees and the Name Clash
A segment tree for intervals works on a known, finite coordinate set, for example the sorted distinct endpoints of all intervals. Each interval is split across O(log n) nodes. A stabbing query walks from the root to one leaf and collects the intervals stored on that path, giving O(log n + k).
The costs are the O(n log n) space and the fixed coordinate set. If new endpoints keep arriving, you must rebuild or use a dynamic variant.
A Static Alternative: Sorted Array with Prefix Max
If the set never changes and you only need to know whether any stored interval overlaps a query, you do not need a tree. Sort by low endpoint. Intervals with a low endpoint at most hi form a prefix of the sorted list. One of them overlaps [lo, hi] exactly when the largest high endpoint in that prefix is at least lo. This is the same max-endpoint idea as the tree, applied to a prefix instead of a subtree.
from bisect import bisect_right
class StaticOverlapIndex:
def __init__(self, intervals):
self.items = sorted(intervals)
self.lows = [lo for lo, _ in self.items]
self.prefix_max = []
best = float("-inf")
for _, hi in self.items:
best = max(best, hi)
self.prefix_max.append(best)
def any_overlap(self, lo, hi):
# Count intervals whose low endpoint is <= hi.
k = bisect_right(self.lows, hi)
return k > 0 and self.prefix_max[k - 1] >= lo
index = StaticOverlapIndex(
[(15, 20), (10, 30), (17, 19), (5, 20), (12, 15), (30, 40)]
)
print(index.any_overlap(21, 23)) # True, (10, 30) overlaps
print(index.any_overlap(45, 50)) # False
print(index.any_overlap(41, 44)) # False, the largest high endpoint is 40Build is O(n log n) and each query is O(log n) from the binary search. It is simpler and faster in practice than a tree because it uses contiguous memory. Any insertion costs O(n) to shift the array and recompute prefix maxima. It also does not list the matching intervals without extra scanning.
Other Structures Worth Knowing
- Sweep line. To find all overlapping pairs in a batch, sort all endpoints and scan once while tracking the set of currently open intervals. This takes O(n log n + k), where k counts pairs. It needs no persistent index, but it answers only that one batch question.
- Priority search tree. It answers queries of the form "x in a range and y at least a threshold." Mapping an interval to the point (low, high) turns some interval queries into that form. Its bound is O(log n + k).
- R-tree. An R-tree groups boxes in several dimensions and is common in databases and spatial indexes. It handles two- and three-dimensional rectangles well but gives weaker worst-case guarantees than the one-dimensional trees above.
- Library implementations. Python's
intervaltreepackage and many database engines use variants of the structures in this chapter. Read the documentation for the complexity they actually promise.
Choosing a Structure
Use these criteria in order:
- Update rate. Frequent inserts and deletes with arbitrary endpoints point to the balanced augmented BST.
- Query type. Stabbing queries on a fixed grid of coordinates favor a segment tree. One-hit existence checks on static data favor the sorted array.
- Output size. If queries often return thousands of intervals, an O(log n + k) structure beats O(k log n). If most queries return zero or one result, the difference disappears.
- Memory. The O(n log n) space of a segment tree matters when n is in the tens of millions.
- Implementation cost. The augmented BST needs a balanced tree underneath. Reusing an existing red-black or AVL tree and adding the max field is often the cheapest route.
Common Mistakes
- Choosing a segment tree for a dynamic set, then discovering that new endpoints force a rebuild.
- Quoting O(log n + k) for the augmented BST. The simple traversal does not guarantee that bound.
- Forgetting that rotations in the balanced tree must recompute
maxfor the two nodes whose subtrees changed. - Using the static prefix-max index after inserting into the underlying list without recomputing it.
Exercise
Your service stores 2 million meeting-room bookings as closed intervals. Bookings are added and cancelled all day, and the only question asked is "is any existing booking overlapping this proposed slot?" Which structure would you choose, and why not a segment tree or the sorted-array index?
Show answer
Use a balanced augmented BST (an interval tree). The set changes constantly, so updates must be cheap: O(log n) for insert and delete, and O(log n) to find one overlap, which is all the question needs. The sorted-array index would cost O(n) per insertion or cancellation. A segment tree needs a fixed coordinate set and O(n log n) space, and it does not suit arbitrary new slot boundaries without rebuilding.
Exercise
A reporting job loads 50 million read-only intervals once and then runs billions of stabbing queries, each returning many intervals. Which structure fits best, and what bound makes it fit?
Show answer
A centered interval tree, because the data is static and each query returns many results. It uses O(n) space and answers each stabbing query in O(log n + k), so the per-result cost is constant. A segment tree also gives O(log n + k), but its O(n log n) space is costly at 50 million intervals. The augmented BST's pruned traversal gives only O(k log n).