Sub topic 1
Intervals and Their Endpoints
This chapter sets up the vocabulary for the rest of the tutorial. It defines what an interval is, which conventions the later chapters rely on, and which small operations you will use again and again. The overlap test, the tree itself, and the search algorithms come in later chapters.
Prerequisites
This chapter assumes you already know the following:
- Binary search trees: ordering, insertion, search, and in-order traversal.
- Big-O notation and the idea of tree height.
- Basic recursion.
- How to read short Python code.
You do not need to know anything about interval trees yet.
What an Interval Is
An interval is a contiguous range of values on a line, described by two numbers. The smaller number is the low endpoint. The larger number is the high endpoint. We write an interval as [lo, hi], and we always require lo <= hi.
Intervals appear whenever something has a start and an end:
- A meeting from 9:00 to 10:30 is an interval on a time axis.
- A range of IP addresses, such as 10.0.0.0 through 10.0.0.255, is an interval on an address axis.
- A gene on a chromosome covers an interval of positions.
- A run of memory pages that a program has reserved is an interval of page numbers.
In all of these cases we often need to ask how one range relates to another. Interval trees exist to answer one such question quickly: which stored ranges overlap a given range?
Closed Intervals
Intervals can include or exclude their endpoints. This tutorial uses closed intervals. A closed interval [lo, hi] contains every value x with lo <= x <= hi, so both endpoints belong to it.
The other common conventions are:
| Convention | Notation | Contains x when |
|---|---|---|
| Closed | [lo, hi] | lo <= x <= hi |
| Open | (lo, hi) | lo < x < hi |
| Half-open | [lo, hi) | lo <= x < hi |
The choice matters most when two intervals touch at a single point. Under the closed convention, [5, 9] and [9, 12] share the value 9, so they overlap. Under the half-open convention, [5, 9) and [9, 12) share nothing, so they do not. Calendar software often uses half-open ranges for this reason: a meeting that ends at 10:00 and one that starts at 10:00 do not conflict.
Representing Intervals in Code
In Python, the simplest representation is a tuple of two numbers. A named tuple adds readable field names without extra cost, and it is still immutable.
from typing import NamedTuple
class Interval(NamedTuple):
lo: float
hi: float
def make_interval(lo, hi):
# Reject malformed input at the boundary, not deep inside the tree.
if lo > hi:
raise ValueError(f"low endpoint {lo} is greater than high endpoint {hi}")
return Interval(lo, hi)
meeting = make_interval(9, 10.5)
print(meeting) # Interval(lo=9, hi=10.5)
print(meeting.lo) # 9
print(meeting.hi) # 10.5
print(meeting.hi - meeting.lo) # 1.5, the length of the intervalValidating lo <= hi when you create an interval is worth the one line. Every algorithm later in this tutorial assumes the invariant holds. If a reversed interval such as (10, 5) gets into a tree, searches can return wrong answers without raising any error.
Degenerate Intervals
A degenerate interval has lo == hi. It is a single point, written [7, 7]. Under the closed convention it is valid and contains exactly one value.
Degenerate intervals are useful because they let you treat a point as a special case of an interval. Asking "which stored intervals contain the value 7?" is the same as asking "which stored intervals overlap [7, 7]?" Later chapters call this a stabbing query. Under the half-open convention a point interval [7, 7) would be empty, which is one more reason this tutorial uses closed intervals.
Intervals Have Two Orderings
Points on a line have one natural order. Intervals have at least two, because each interval has two endpoints.
- Order by low endpoint: [3, 8] comes before [5, 6], because 3 < 5.
- Order by high endpoint: [5, 6] comes before [3, 8], because 6 < 8.
These orders disagree whenever one interval contains another. This disagreement is the central difficulty of the topic. A binary search tree can sort intervals by only one key, and the interval tree will sort by the low endpoint. Sorting by low endpoint tells you where an interval starts. It tells you nothing about how far the interval extends to the right. A [1, 100] stored near the left of the tree can still overlap a query far to the right.
from typing import NamedTuple
class Interval(NamedTuple):
lo: float
hi: float
intervals = [Interval(5, 6), Interval(3, 8), Interval(1, 100), Interval(7, 9)]
by_low = sorted(intervals, key=lambda iv: iv.lo)
by_high = sorted(intervals, key=lambda iv: iv.hi)
print(by_low)
# [Interval(lo=1, hi=100), Interval(lo=3, hi=8), Interval(lo=5, hi=6), Interval(lo=7, hi=9)]
print(by_high)
# [Interval(lo=5, hi=6), Interval(lo=3, hi=8), Interval(lo=7, hi=9), Interval(lo=1, hi=100)]Both lists contain the same four intervals, but they appear in different orders. In the first list, [1, 100] comes first even though it reaches farther right than any other interval.
Ties Between Endpoints
Real data contains duplicates. Two intervals can share a low endpoint, share a high endpoint, or be completely identical. Your design has to decide what to do:
- Several intervals with the same low endpoint are legitimate. The tree must allow equal keys. The insertion code in this tutorial sends an equal low endpoint to the right subtree.
- Fully identical intervals are either stored twice or rejected, depending on the application. A booking system might need both entries. A set of merged ranges would reject the duplicate.
- Attaching extra data, such as a meeting title, to each interval lets you tell identical ranges apart.
Python tuples compare element by element, so sorting a list of (lo, hi) pairs breaks ties on lo by comparing hi. That behavior is convenient, but the algorithms in this tutorial do not depend on it.
A Picture of Intervals on a Line
The diagram below shows the relationships that two intervals can have. The overlap test in the next chapter must recognize every case in the "overlap" group and reject every case in the "disjoint" group.
Touching at one endpoint belongs in the overlapping group only because we chose closed intervals. With half-open intervals it would move to the disjoint group.
Common Mistakes
- Forgetting to validate lo <= hi, which lets malformed intervals corrupt later searches silently.
- Mixing endpoint conventions between the code that creates intervals and the code that compares them.
- Assuming that sorting by low endpoint also sorts by high endpoint. It does not, and the next chapters build on this fact.
- Using floating-point endpoints and comparing them for equality. Rounding error can make two ends that should touch miss each other. Use integers, such as milliseconds, where you can.
What Comes Next
The next chapter turns these definitions into a precise overlap test, a single comparison expression that works for every case in the diagram above. Later chapters then show why scanning every interval is too slow and how a tree built on the low endpoint, with extra bookkeeping, gives fast answers.
Exercise
Under the closed-interval convention, do [2, 6] and [6, 10] share a value? Would your answer change if both intervals were half-open, written [2, 6) and [6, 10)? Also, which of the two sort orders (by low endpoint or by high endpoint) puts [1, 100] first in the list [(5, 6), (3, 8), (1, 100), (7, 9)]?
Show answer
With closed intervals they share the value 6, so they touch and overlap. With half-open intervals, 6 belongs only to the second interval, so they share nothing and do not overlap. Sorting by low endpoint puts [1, 100] first. Sorting by high endpoint puts it last, because 100 is the largest high endpoint.
Exercise
Write a Python function is_valid(iv) that returns True when a (lo, hi) tuple is a valid closed interval, and say whether (4, 4) is valid.
Show answer
def is_valid(iv): return iv[0] <= iv[1]. The tuple (4, 4) is valid. It is a degenerate interval that contains only the value 4.