Sub topic 1
Intervals and Their Endpoints
Prerequisites
Assume you know binary search trees, recursion, tree height, and Big-O notation. You should also be able to read short Python functions.
Intervals and Their Endpoints
An interval is a range between two endpoints. A closed interval includes both endpoints, so [3, 7] contains 3, 5, and 7. We represent it in Python as (low, high), where low <= high.
An interval tree stores many intervals and supports queries such as “which stored interval overlaps this one?” The endpoints have different jobs:
lowdetermines the interval's ordering in a search tree.highhelps determine whether intervals overlap.- A query interval also has a low and high endpoint.
def overlaps(a, b):
# a and b are closed intervals: (low, high)
return a[0] <= b[1] and b[0] <= a[1]
print(overlaps((15, 20), (10, 30))) # True
print(overlaps((5, 8), (9, 12))) # False
print(overlaps((5, 9), (9, 12))) # TrueTesting Whether Two Intervals Overlap
Two closed intervals overlap when neither one lies completely to the left of the other. The test is:
a.low <= b.high and b.low <= a.high
The comparison is inclusive because intervals sharing an endpoint overlap. For example, [5, 9] and [9, 12] overlap at 9.
The Problem: Overlap and Stabbing Queries
An overlap query asks which stored intervals intersect a query interval. A stabbing query asks which stored intervals contain one point, such as 18.
Why a Linear Scan Is Not Enough
The simplest method checks every stored interval. With n intervals, one query takes O(n) time. This becomes slow when queries are frequent or the collection is large.
Sorting by low endpoint alone does not solve the problem. An interval with a small low endpoint may extend far to the right, so low endpoints do not reveal whether a later interval can overlap. An interval tree adds subtree information to prune impossible branches.
Quick Review: Binary Search Trees
A binary search tree (BST) places smaller keys in the left subtree and larger keys in the right subtree. If intervals are ordered by low, an in-order traversal lists them by their low endpoints.
A plain BST gives useful ordering, but it does not quickly answer overlap queries. The next step is to augment each node with the largest high endpoint anywhere in its subtree.
Exercise
Do the closed intervals [2, 5] and [5, 9] overlap?
Show answer
Yes. They share the endpoint 5.