Quadtree
A tree that splits a rectangle of the map into four equal quadrants, and splits any quadrant that holds too many points again, so dense areas get small cells and empty areas stay as one big cell. It exists because a fixed grid wastes effort where nothing is and overflows where everything is.
What it costs
| Operation | Cost | Note |
|---|---|---|
| Insert a point | O(depth) | Descend to the leaf covering the point; split the leaf if it exceeds the capacity. |
| Range query (rectangle) | O(depth + k) | Descend only into quadrants that overlap the rectangle; k is the number of results. |
| k nearest | O(depth + k log k) | Search the leaf, then expand to sibling quadrants until k found and the rest cannot be closer. |
| Move a point | O(depth) × 2 | Delete from the old leaf, insert into the new one; may trigger a merge and a split. |
Memory: One node per quadrant that was ever split plus the points in the leaves. 200,000 restaurants with a leaf capacity of 50 gives about 5,000 leaves and 7,000 nodes: a few megabytes, almost all of it the points themselves.
Dense quadrants split again; empty ones stay whole
The root covers the city. The crowded north-east quarter has been split twice so its leaves are small; the sparse south-west is a single leaf. A query descends only into quadrants that overlap it.
How it works
- The root covers the whole area of interest (a city, a country). Each node is either a leaf holding up to C points (say 50), or an internal node with exactly four children: north-west, north-east, south-west, south-east, each covering a quarter of the parent’s rectangle.
- To insert a point, start at the root and descend into whichever child rectangle contains it, until you reach a leaf. Add the point there. If the leaf now holds more than C points, split it into four children and move its points down into them.
- The result is deep where points are dense (downtown splits ten levels) and shallow where they are sparse (a desert is one leaf). Cell size adapts to the data, which a geohash grid cannot do.
- To find everything in a search rectangle, start at the root and descend only into children whose rectangle overlaps the search area; skip the others entirely. Leaves you reach are scanned and points filtered exactly.
- For k nearest, find the leaf containing the query point, collect its points, and expand outward into neighbouring quadrants in order of distance, stopping when the closest unexplored quadrant is farther than the k-th best point found.
- When points leave a leaf and the four siblings together drop under C, merge them back into their parent so the tree does not keep empty structure.
Why it is shaped this way
- Adaptive subdivision keeps every leaf small regardless of density, so a query reads a handful of leaves whether it is in Manhattan or Montana.
- The rectangle test at each node prunes whole regions in one comparison, which is what makes range queries logarithmic instead of linear.
Worked example
Restaurants versus drivers
- 200K restaurants in a metro, leaf capacity 50. Downtown has 20K restaurants in 4 km²: that quadrant splits about 9 levels until leaves are roughly 80 m across (400 leaves of up to 50 points covering 4 km²). The outskirts with 2 restaurants per km² stay at level 4, cells 2.5 km across. About 5,000 leaves, 7,000 nodes total, built once in a few hundred milliseconds.
- "Restaurants within 500 m": a 1 km × 1 km rectangle around the user. Downtown it overlaps about 150 small leaves holding roughly 5,000 candidates; filtering by true distance keeps about 3,900 inside the circle. In the suburbs it overlaps 1 leaf of 12 points. Both queries cost a descent of under 10 nodes plus the leaf scans, well under a millisecond in memory.
- Restaurants change rarely (a few hundred inserts a day), so the tree is effectively static. Rebuild nightly, serve from memory in every API server.
- Now try 50K drivers updating every 4 s: 12,500 moves per second, each a delete and an insert, with splits and merges as drivers cluster at a stadium. Under a global lock that is a contended structure; without one it is hard to keep consistent. This is why moving objects use a geohash sorted set instead and quadtrees stay for things that sit still.
When it is the wrong choice
- Points that move constantly (drivers, delivery riders): every move is a delete and insert with possible splits and merges, under contention. Use a geohash or H3 cell index in a sorted set.
- Data spread across many servers: a tree is one in-memory structure; sharding it means cutting it into regions anyway, at which point cells are simpler.
- Polygons and routes rather than points: an R-tree stores bounding boxes of shapes; a quadtree is for point data.
Interviewer follow-ups
Answer out loud before you open each one.
Why does a quadtree suit restaurants but not drivers?
Restaurants rarely move, so the tree is built once and only read; its adaptive cells make downtown and countryside queries equally cheap. Drivers move every few seconds, and each move is a delete plus insert that can split or merge nodes, which is expensive and hard to do concurrently. Cell-based indexes update a point in one O(log n) write.
How do you choose the leaf capacity?
Large enough that a leaf scan is cheap and the tree stays shallow, small enough that a query over a few leaves does not return thousands of candidates. Values from 20 to 100 are typical; measure the average candidates per query and the depth downtown and tune from there.
How does a nearest-neighbour search know when to stop?
Keep the k best distances found so far. Explore quadrants in order of their minimum possible distance to the query point. Once the next quadrant’s minimum distance exceeds the k-th best found, nothing in it or beyond can improve the answer, so stop.
What is the difference between a quadtree and an R-tree?
A quadtree splits space into fixed quarters regardless of the data; an R-tree groups nearby objects into bounding boxes that can overlap and are chosen from the data. R-trees handle shapes with extent (roads, polygons) and are what PostGIS uses; quadtrees are simpler and fine for points.
Where it shows up
- Building blocks
- Find things near a point · Full-text and fuzzy search
- Problems
- Ride Matching (Uber / Lyft)