Sub topic 1
The Problem: Finding Nearby Points Without Scanning Everything
Prerequisites
This chapter assumes you know:
- Big-O notation for time and space.
- Basic Python: functions, tuples, lists and comprehensions.
- Coordinates, Euclidean distance and axis-aligned rectangles (rectangles whose sides are parallel to the axes).
Later chapters use binary search trees and recursion. This chapter doesn't.
Two questions about points
Spatial data is a collection of points with coordinates, such as store locations, game objects or sensor readings. Two queries come up constantly:
- Range search returns every point inside a region, usually an axis-aligned rectangle. Example: all taxis inside the visible map window.
- Nearest-neighbor search returns the stored point closest to a target point. Example: the closest charging station to a car.
Both are easy to write. The difficulty is doing them many times on a large dataset.
The linear scan baseline
The simplest approach checks every point.
import random
def range_scan(points, xmin, ymin, xmax, ymax):
return [p for p in points
if xmin <= p[0] <= xmax and ymin <= p[1] <= ymax]
def nearest_scan(points, target):
return min(points,
key=lambda p: (p[0] - target[0]) ** 2 + (p[1] - target[1]) ** 2)
random.seed(1)
points = [(random.random() * 100, random.random() * 100)
for _ in range(100_000)]
hits = range_scan(points, 10, 10, 12, 12)
print(len(hits)) # about 40 points
print(nearest_scan(points, (50, 50)))nearest_scan compares squared distances. Squaring preserves the ordering, so you can skip the square root.
Both functions are correct and take O(n) time for n points. They examine every point, even though the answer lives in a tiny corner of the space.
Why O(n) becomes a problem
A single scan of 100,000 points is fast enough. The cost appears when queries repeat:
| Points (n) | Queries (q) | Distance or bounds checks |
|---|---|---|
| 1,000 | 1,000 | 1 million |
| 100,000 | 1,000 | 100 million |
| 10,000,000 | 10,000 | 100 billion |
The work grows as q × n. In pure Python, the middle row already takes seconds to tens of seconds. The last row is impractical on a single machine.
Most of that work is wasted. In the range query above, the rectangle covers about 0.04% of the square, yet the scan tests the other 99.96% of the points and rejects them.
The idea: discard whole groups at once
If you knew in advance where points lived, you could rule out large groups without looking at them. Suppose the points are sorted into regions. A query for the rectangle near (10, 10) can skip every region far from it. Only the few regions that overlap the rectangle need a point-by-point check.
Splitting space into regions and skipping the irrelevant ones is called pruning. The structures in this tutorial differ in how they split space:
- A k-d tree cuts the points in half along one coordinate at a time.
- A quadtree cuts a square into four equal quadrants.
Pruning does not make every query fast. Its benefit depends on how the points are distributed and where the query lands. The complexity chapter returns to this.
What you will build
Over the next chapters you will build a k-d tree and a quadtree in Python. You will write range search and nearest-neighbor search on the k-d tree. You will write insertion and range queries on the quadtree. Then you will compare their costs and learn when to use a library index instead.
Exercise
A game has 50,000 static obstacles and runs 2,000 "which obstacles are in this rectangle?" queries per frame. How many point checks does a linear scan do per frame, and why does that suggest an index?
Show answer
50,000 × 2,000 = 100 million checks per frame. The obstacles never move, so the cost of building an index is paid once. Each query can then skip most obstacles by pruning regions far from the rectangle.