Sub topic 4
Why a Linear Scan Is Not Enough
This chapter assumes you know the closed-interval overlap test from the earlier chapters. It also assumes you can read short Python and use Big-O notation. Here you will price the obvious approach to overlap queries, a scan over every stored interval. You will also see why sorting the intervals by low endpoint does not fix it.
The obvious solution
Suppose you store intervals as (low, high) pairs in a list. A query asks for every stored interval that overlaps [lo, hi]. The overlap test you already have gives a direct answer: check each interval.
def scan_overlaps(intervals, lo, hi):
# Returns every stored interval that overlaps the closed interval [lo, hi].
return [iv for iv in intervals if iv[0] <= hi and lo <= iv[1]]
bookings = [(9, 10), (13, 15), (9, 17), (16, 18)]
print(scan_overlaps(bookings, 14, 14)) # [(13, 15), (9, 17)]
print(scan_overlaps(bookings, 19, 20)) # []This code is correct, short, and hard to get wrong. For a few hundred intervals and a few queries, it is the right choice. Using anything more complicated at that size is a mistake.
What the scan costs
The scan applies the overlap test once to each of the n stored intervals, so one query costs O(n). The scan cannot stop early when you want every overlap, because any interval, including the last one, might be a match. Even when you want only one overlap, a scan can examine all n intervals whenever no interval overlaps.
The table compares the scan with what you will build in the next chapters. The k is the number of intervals the query reports.
| Operation | Unsorted list | Interval tree (balanced) |
|---|---|---|
| Insert one interval | O(1) | O(log n) |
| Find one overlap | O(n) | O(log n) |
| Report all overlaps | O(n) | O(k + log n) |
| Delete one interval | O(n) to find it | O(log n) |
Unsorted-list insertion is cheaper than tree insertion, and you should notice that. If you insert often and query rarely, the list may win. The tree pays off when queries are frequent and the set is large.
Here is the cost at a realistic size. Say you store 1,000,000 intervals and run 1,000 queries.
- The scan performs about 1,000,000 × 1,000 = 10^9 overlap tests.
- A balanced tree follows one root-to-leaf path of about log2(1,000,000) ≈ 20 nodes per single-overlap query. That is about 20,000 steps in total.
The gap grows with n. Doubling the data doubles the scan's work, but it adds only one step to each tree query.
Why the data being dynamic matters
If the set never changed, you could preprocess it once and answer all queries from the result. The problem in this tutorial is a dynamic set. Intervals arrive and leave between queries, as with meeting bookings, active network connections, or reserved memory ranges. A structure that is fast to query but needs an O(n) rebuild after each change does not help. That is why a tree is the target. It supports insertion, deletion, and querying, each in O(log n).
The tempting fix: sort by low endpoint
A natural idea is to keep the list sorted by low endpoint and use binary search. This works well for point lookups on ordinary keys, so it seems worth trying here.
Binary search on the low endpoints tells you one thing quickly. It finds the intervals with low <= hi, which form a prefix of the sorted list. Everything after that prefix starts after the query ends, so it cannot overlap.
The problem is the other half of the overlap test. Inside the prefix, you still need lo <= high for each interval. The high endpoints are not sorted, so binary search cannot help with them. Look at this case.
from bisect import bisect_right
intervals = [(1, 100), (2, 3), (4, 5), (6, 7), (8, 9), (10, 11)] # sorted by low
q_lo, q_hi = 50, 60
lows = [iv[0] for iv in intervals]
prefix = bisect_right(lows, q_hi) # how many intervals have low <= 60
print(prefix) # 6
hits = [iv for iv in intervals[:prefix] if q_lo <= iv[1]]
print(hits) # [(1, 100)]All six intervals pass the low <= hi filter, but only (1, 100) overlaps the query. The binary search ruled out nothing, and you still check every interval. One long interval near the front is enough to keep the rest of the prefix undecided. The worst case remains O(n).
Sorting by high endpoint instead fails by the mirror-image argument. The sort then gives you the suffix with high >= lo, and the lows inside it are unordered. One sort order cannot serve both inequalities.
What a better structure needs
The failed attempt shows what is missing. After you order intervals by low endpoint, you need a cheap way to learn whether any interval in a group reaches far enough to the right to touch the query. In the example above, a single number would have answered it. The largest high endpoint among (2, 3) through (10, 11) is 11, which is less than 50. So none of those five can overlap [50, 60], and you can skip them without looking at each one.
That summary value is the idea behind the next chapters. You will keep intervals in a binary search tree ordered by low endpoint. You will store at each node the maximum high endpoint found in its subtree. The ordering handles one inequality, and the stored maximum handles the other.
Common mistakes at this stage
- Optimizing too early. If
nis small or queries are rare, the scan is simpler and often faster in practice because of its low constant factors. Measure before building a tree. - Treating "sorted" as "indexed." A list sorted by low endpoint has no useful index for the high endpoint, as the example showed.
- Ignoring output size. If a query matches most of the stored intervals, any method must take Ω(k) time to report them. Interval trees help most when
kis much smaller thann.
Exercise
A system holds 2,000,000 intervals and receives 5,000 overlap queries, and each query asks for one overlapping interval (or none). Roughly how many overlap tests does a linear scan perform in the worst case, and roughly how many nodes does a balanced tree visit at most? Then explain in one sentence why a list sorted by low endpoint does not rescue the scan.
Show answer
The scan performs up to 2,000,000 × 5,000 = 10^10 overlap tests. A balanced tree has height about log2(2,000,000) ≈ 21, so it visits at most about 5,000 × 21 ≈ 105,000 nodes, around 100,000 times less work. Sorting by low endpoint lets binary search discard only the intervals that start after the query ends, so a long early interval can leave almost the whole list as candidates, and the high endpoints are unordered, so each candidate still needs its own check.