Sub topic 14
Time and Space Complexity
This chapter assumes you can read the interval tree code from the earlier chapters: the Node class with its max field, insert, find_overlap, and find_all. It also assumes you know Big-O notation and that a binary search tree (BST) of height h costs O(h) per operation. Here we put exact costs on each operation and show where the O(log n) guarantee comes from and when it fails.
The Short Version
Let n be the number of stored intervals, h the tree height, and k the number of intervals that overlap a query.
| Operation | Plain list | Interval tree (balanced) | Interval tree (unbalanced, worst case) |
|---|---|---|---|
| Insert | O(1) | O(log n) | O(n) |
| Delete | O(n) to find it | O(log n) | O(n) |
| Find one overlap | O(n) | O(log n) | O(n) |
| Report all overlaps | O(n) | O(min(n, (k + 1) log n)) | O(n) |
| Space | O(n) | O(n) | O(n) |
Every tree cost is O(h). The whole question is how large h is, and that depends on balancing.
Why Each Operation Costs O(h)
All the operations walk a single root-to-leaf path, doing a constant amount of work at each node.
- Insert descends by low endpoint, as in a normal BST. On the way back up it runs
node.max = max(node.max, hi), which is one comparison per level. That is O(h) in total. - Find one overlap performs one overlap test and one comparison with
node.left.maxat each node, then moves to exactly one child. It never backtracks, so it visits at most h nodes. The earlier chapter on search correctness explains why this is safe. - Delete finds the node in O(h), removes it using the usual BST cases, and then recomputes
maxfor each node on the path back up. Recomputingmaxmeans taking the largest of the node's ownhi, its left child'smax, and its right child'smax. That is still O(1) per node. - Rotations change only two nodes. Recompute the lower one first, then the upper one, and the cost is O(1) per rotation.
The augmentation costs nothing asymptotically. The max field is O(1) to update per node, and only the nodes whose subtrees changed need updating.
Reporting All Overlaps: Output-Sensitive Cost
find_all is different, because its cost depends on the answer size k as well as on n. A query that overlaps nothing should be cheap. A query that overlaps everything must take at least k steps, since it has to return k intervals.
The pruning rule in find_all skips a subtree when node.max < lo. It skips the right subtree when node.lo > hi. Two facts bound the work:
- If a visited node's left subtree contains no overlap but still has
max >= lo, then some interval there has a low endpoint abovehi. Every interval in the right subtree has an even larger low endpoint, so the right subtree is skipped. A fruitless visit therefore leads down a single path. - Each of the k reported intervals can cause at most one such path of length h.
This gives O((k + 1) log n) for a balanced tree. The "+ 1" covers k = 0, which costs a single O(log n) path. The cost is also never worse than O(n), since each node is visited at most once, so the bound is O(min(n, (k + 1) log n)).
This is a safe upper bound, not a tight one. More careful designs reach O(log n + k), but they need extra machinery that the simple augmented tree does not have.
A stabbing query (which intervals contain the point x?) is an overlap query with lo = hi = x, so it has the same costs.
Measuring It
The next program builds one tree from random intervals and one from sorted intervals. It prints the height of each and counts the nodes find_all visits.
import random
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 height(node):
if node is None:
return 0
return 1 + max(height(node.left), height(node.right))
def find_all(node, lo, hi, out, stats):
if node is None or node.max < lo:
return
stats[0] += 1 # count visited nodes
find_all(node.left, lo, hi, out, stats)
if node.lo <= hi and lo <= node.hi:
out.append((node.lo, node.hi))
if node.lo <= hi:
find_all(node.right, lo, hi, out, stats)
def build(intervals):
root = None
for lo, hi in intervals:
root = insert(root, lo, hi)
return root
random.seed(1)
n = 500
intervals = [(lo, lo + random.randint(1, 20)) for lo in random.sample(range(10000), n)]
shuffled_root = build(intervals)
sorted_root = build(sorted(intervals))
print("height, random order:", height(shuffled_root))
print("height, sorted order:", height(sorted_root)) # 500
for name, root in (("random", shuffled_root), ("sorted", sorted_root)):
out, stats = [], [0]
find_all(root, 5000, 5010, out, stats)
print(name, "tree: reported", len(out), "visited", stats[0], "of", n)The sorted-order tree has height exactly 500, because every new low endpoint is larger than all earlier ones and goes to the right. The random-order tree has a height of a few dozen at most. Both trees return the same overlaps. The sorted tree, however, visits many more nodes, because its chain-shaped structure means each pruning decision removes at most one node.
The recursion in insert and height is limited by Python's default recursion depth of about 1000. This is also a practical warning. A degenerate tree can crash a recursive implementation before it merely runs slowly.
Balancing: What Guarantees h = O(log n)
Plain BST insertion keeps h small only on average, and only if keys arrive in random order. Sorted or nearly sorted input, which is common for time-ordered events, produces a chain. To get worst-case guarantees, use a self-balancing tree and add the max update to its rotations:
| Balancing scheme | Height bound | Notes for interval trees |
|---|---|---|
| AVL tree | about 1.44 log2 n | Strict balance, more rotations on update |
| Red-black tree | at most 2 log2(n + 1) | At most 3 rotations per insert, which suits update-heavy workloads |
| Treap (random priorities) | O(log n) expected | Simple code, no worst-case guarantee |
Balancing does not change the cost of the search code at all. It only changes h.
Space Complexity
An interval tree stores one node per interval, and each node holds two endpoints, a max field, and two child pointers. That is O(1) per node and O(n) in total. The augmentation adds one number per node, not a separate structure.
Extra space beyond the nodes is O(h) for the call stack in recursive code. An iterative find_overlap, like the one in this tutorial, uses O(1) extra space. find_all also needs O(k) space for its output list.
Building the tree from n intervals by repeated insertion takes O(n log n) time on a balanced tree.
Common Mistakes
- Quoting O(log n) for an unbalanced tree. The bound holds only if the height does.
- Forgetting that
find_alldepends on k. Calling it O(log n) is wrong when k is large. - Updating
maxon insertion but not on deletion or rotation. A stalemaxsilently breaks the pruning rule and the answers, not just the speed. - Treating a lower-bound intuition as an upper one. The tree beats a list only when queries are frequent. For a one-off query on a static set, a single O(n) scan is cheaper than building the tree.
Exercise
A balanced interval tree holds 1,000,000 intervals. A query overlaps k = 3 of them. Using the bound O((k + 1) log n), roughly how many node visits (up to a constant factor) should you expect at most, and how does that compare with a linear scan?
Show answer
log2(1,000,000) is about 20, so (3 + 1) × 20 = about 80 node visits, times a small constant. A linear scan checks all 1,000,000 intervals, so the tree is roughly 10,000 times less work at this scale.
Exercise
A programmer inserts 10,000 intervals into an interval tree in order of increasing low endpoint, with no balancing. What is the height, and what does a find-one-overlap query cost in the worst case?
Show answer
The height is 10,000, because each new interval goes to the right of the previous one, forming a chain. A query can walk the entire chain, so it costs O(n), the same order as a linear scan. A self-balancing tree such as a red-black tree would keep the height near 14 (log2 of 10,000) and the query cost near 14 steps.