Sub topic 10
Expected costs and worst cases
This chapter assumes you know Big-O notation, the k-d tree and quadtree code from the earlier chapters, and basic probability intuition ("average case" versus "worst case"). Here n is the number of points, k is the number of points a query returns, and d is the number of dimensions.
Why a linear scan is the baseline
A linear scan checks every point, so a range query or nearest-neighbor query costs O(n). A spatial index is worth building only if its queries usually cost much less than that. "Usually" is the important word. Both structures give good guarantees only when the data cooperates.
Costs of a k-d tree
Median splitting puts half the points on each side of every node. The tree height is therefore about log2(n), and exactly n.bit_length() levels when built from n points. Every cost below follows from that balance.
- Build: the earlier code sorts at every level, so it costs O(n log² n). Using a linear-time median selection instead gives O(n log n).
- Range search: O(n^(1-1/d) + k). In 2-d that is O(√n + k). A query rectangle can touch about √n cells along its boundary, even when it returns few points.
- Nearest neighbor: O(log n) expected for well-spread points in low dimensions. The search goes down one path, then backtracks only into the few far sides that could hold a closer point.
- Worst case for nearest neighbor: O(n). If the best distance is large compared with the cell sizes, the splitting-plane test
diff * diff < best[0]passes almost everywhere and nothing is pruned.
Costs of a quadtree
A quadtree splits by position, not by count, so its shape depends on where the points lie.
- Uniform data: each level divides the cell area by 4, so depth is about log4(n / capacity). Range queries cost O(depth + k) plus the cells along the query border.
- Clustered data: points packed into a tiny region keep landing in the same quadrant. The tree grows a long chain of subdivisions, and depth is limited only by
max_depth. - Duplicate points: identical points can never be separated. Without a depth limit, a cell holding more than
capacitycopies would subdivide forever. Themax_depthguard in the earlier code prevents this, at the price of leaves that hold many points and are scanned linearly.
The sketch below measures that depth difference. It is self-contained and counts only subdivision depth.
import random
def quad_depth(points, cx, cy, half, capacity=2, max_depth=20):
if len(points) <= capacity or max_depth == 0:
return 0
quadrants = {}
for x, y in points:
quadrants.setdefault((x >= cx, y >= cy), []).append((x, y))
h = half / 2
return 1 + max(
quad_depth(pts, cx + (h if right else -h), cy + (h if up else -h),
h, capacity, max_depth - 1)
for (right, up), pts in quadrants.items()
)
random.seed(1)
uniform = [(random.uniform(0, 100), random.uniform(0, 100)) for _ in range(1000)]
clustered = [(random.uniform(10, 10.01), random.uniform(10, 10.01)) for _ in range(1000)]
print("uniform depth: ", quad_depth(uniform, 50, 50, 50))
print("clustered depth:", quad_depth(clustered, 50, 50, 50))Run it and compare the two numbers. The clustered set has the same n but needs a much deeper tree, because the first many splits all put every point in one quadrant.
Summary of costs
| Operation | K-d tree (balanced) | Quadtree (uniform) | Bad case |
|---|---|---|---|
| Build | O(n log n) to O(n log² n) | O(n log n) | Quadtree depth grows with clustering |
| Range query | O(n^(1-1/d) + k) | O(depth + k) plus border cells | O(n) if the range covers most points |
| Nearest neighbor | O(log n) expected | similar, depends on the search | O(n) when pruning fails |
Exercise
You build a quadtree with capacity 2 and max_depth 10. You then insert 500 copies of the same point (30, 30). What is the tree's depth, and what does a range query that includes (30, 30) cost?
Show answer
The depth reaches 10. The cell holding the copies keeps subdividing until max_depth stops it, and the copies can never be separated. That leaf then holds all 500 points. A query that reaches it scans them one by one, so it costs O(500) for that leaf, which is linear in the number of duplicates.