Build a Bucketed Spatial Index for Planar Points
Data Structure DesignModel answerLast updated
Implement a region quadtree that stores 2D points in capacity-limited buckets, splits into four quadrants on overflow, and answers rectangular range queries efficiently.
Spatial Index with Quadrant Splitting
Build a Quadtree class that stores 2D points inside a fixed rectangular region and supports fast rectangular range lookups.
Structure
Each node of the tree represents a rectangle described by its bottom-left origin and its size (x, y, width, height). A node holds:
boundary: the rectangle it covers.points: the points stored directly in the node.children: eithernull/None, or a list of four sub-rectangles (northwest, northeast, southwest, southeast).
Operations
insert(x, y): put a point into the tree. A node may keep at most 4 points. When a node would exceed that limit, it divides into four equal quadrants and its points are redistributed among them.query(range_x, range_y, range_w, range_h): given a query rectangle (bottom-left corner plus width and height), return every stored point lying inside it.
Conventions and constraints
- Node capacity is 4.
- Coordinates are floating-point numbers.
- The x axis grows to the right, the y axis grows upward, so "north" means larger
y.
Example
qt = Quadtree(0, 0, 100, 100) # region from (0,0), 100 wide and 100 tall
qt.insert(10, 10)
qt.insert(20, 20)
qt.query(0, 0, 15, 15) # -> [(10, 10)]
Cases you should handle explicitly
- Points that lie exactly on a line separating two quadrants.
- Many insertions of the same coordinate.
- Heavily clustered data, such as every point in one corner.
What to deliver
Write the implementation, explain how you decide which quadrant a point belongs to, state the complexity of both operations, and describe how your design behaves in the cases above.
Hints
Hint 1
A point on the dividing line between quadrants must belong to exactly one child. Pick a single rule, such as comparing against the midpoint with `>=`, instead of testing each child's box for containment.
Hint 2
If more than 4 identical points arrive, splitting can never separate them. Think about what stops the recursion, for instance a maximum depth after which a leaf may exceed its capacity.
Hint 3
For a range query, skip any node whose rectangle does not overlap the query rectangle. Only examine individual points when you reach a leaf, and check them against the query bounds.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A quadtree recursively halves a rectangle. A leaf stores up to CAPACITY = 4 points. When a fifth point arrives, the leaf becomes an internal node: it creates four equal children and pushes its points down. Internal nodes hold no points and only route.
Two design choices matter most.
1. One deterministic routing rule
If every child used a closed box, a point on the midline would be contained in two children and might be stored twice or in an arbitrary one. Instead, route using the midpoint once:
px >= mid_xmeans east, otherwise west.py >= mid_ymeans north, otherwise south.
Each point maps to exactly one child with no gaps. The root still uses an inclusive bounds check, so (100, 100) is valid in a 100x100 region, and points outside the root are rejected.
Because y grows upward, the north children have origin y + h/2 and the south children have origin y. Flipping this is a common bug.
2. A maximum depth
Duplicates (or points that are extremely close) never separate no matter how often you split, so naive code recurses forever. Cap the depth (for example 32). A leaf at the cap simply holds more than 4 points and acts as a bucket.
Query
Traverse from the root. Skip a node if its rectangle does not intersect the query rectangle. At a leaf, test each point against the query bounds (inclusive). Otherwise push the four children.
Why it is correct
- Invariant: every point lives in exactly one leaf, and that leaf's rectangle contains it. Routing uses the same midpoint expression that defines the children's origins, so the invariant holds after every split.
- Completeness: a matching point lies in its leaf, so each ancestor of that leaf overlaps the query and is never pruned.
- Soundness: every returned point is explicitly compared with the query rectangle.
Complexity
Let n be the number of points, k the number returned, D the depth cap.
| Operation | Typical | Worst case |
|---|---|---|
| insert | O(log n) | O(D) descent plus a split cascade bounded by O(D * capacity) |
| query | O(log n + k) | O(n) if the range overlaps most leaves |
| space | O(n) | O(n * D) nodes for tightly clustered data creating chains of mostly empty splits |
For well spread data, depth is about log4(n / capacity). For skewed data, depth depends on the ratio of the region size to the minimum point separation, roughly log2(W / min_gap), rather than on n.
Code
class Node:
__slots__ = ("boundary", "points", "children", "depth")
def __init__(self, x, y, w, h, depth):
self.boundary = (x, y, w, h) # bottom-left origin, y grows upward
self.points = []
self.children = None # [NW, NE, SW, SE] after a split
self.depth = depth
class Quadtree:
CAPACITY = 4
MAX_DEPTH = 32
def __init__(self, x, y, width, height):
self.root = Node(x, y, width, height, 0)
def insert(self, x, y):
bx, by, bw, bh = self.root.boundary
if not (bx <= x <= bx + bw and by <= y <= by + bh):
return False
node = self.root
while node.children is not None:
node = node.children[self._quadrant(node, x, y)]
node.points.append((x, y))
if len(node.points) > self.CAPACITY and node.depth < self.MAX_DEPTH:
self._split(node)
return True
def query(self, range_x, range_y, range_w, range_h):
rx2, ry2 = range_x + range_w, range_y + range_h
out = []
stack = [self.root]
while stack:
node = stack.pop()
x, y, w, h = node.boundary
if range_x > x + w or rx2 < x or range_y > y + h or ry2 < y:
continue # no overlap, prune
if node.children is None:
for px, py in node.points:
if range_x <= px <= rx2 and range_y <= py <= ry2:
out.append((px, py))
else:
stack.extend(node.children)
return out
@staticmethod
def _quadrant(node, px, py):
x, y, w, h = node.boundary
east = px >= x + w / 2
north = py >= y + h / 2
return (0 if north else 2) + (1 if east else 0) # NW=0 NE=1 SW=2 SE=3
def _split(self, node):
x, y, w, h = node.boundary
hw, hh = w / 2, h / 2
d = node.depth + 1
node.children = [
Node(x, y + hh, hw, hh, d), # NW
Node(x + hw, y + hh, hw, hh, d), # NE
Node(x, y, hw, hh, d), # SW
Node(x + hw, y, hw, hh, d), # SE
]
pts, node.points = node.points, []
for px, py in pts:
node.children[self._quadrant(node, px, py)].points.append((px, py))
for child in node.children: # all points may land in one child
if len(child.points) > self.CAPACITY and child.depth < self.MAX_DEPTH:
self._split(child)
On the example, both points stay in the root leaf. The query (0, 0, 15, 15) overlaps the root, checks both points and returns only (10, 10).
Insert and query are iterative, so Python's recursion limit is not a concern. Recursion in _split is bounded by MAX_DEPTH.
Edge cases
- Points on internal split lines: the
>=rule sends each to exactly one quadrant. - Points on the outer border: accepted by the inclusive root check.
- Duplicates: the depth cap stops infinite splitting, and the deepest leaf becomes an oversized bucket.
- Clustered data: correct but deep in one region. The cap bounds the cost.
- Query touching a point exactly: the query is inclusive, so edge points are returned.
- Query larger than or outside the root: pruning handles both with no special code.
Common mistakes
- Using closed boxes for all children, causing double insertion or arbitrary placement on midlines.
- Swapping north and south origins.
- No depth limit, leading to infinite recursion on duplicates.
- Forgetting that a split can send all points to one child, which then needs splitting again.
- Returning whole leaves instead of filtering points against the query.
Follow-ups
- Deletion: descend with the same routing and remove the point. On the way back up, if all four children are leaves and their total is at most the capacity, merge them into the parent. Merging at a lower watermark (such as half the capacity) avoids thrashing around the threshold.
- Nearest neighbor: run a best-first search using a priority queue keyed by the minimum distance from the query point to each node's rectangle.
- Many duplicates: store a count per coordinate instead of repeating the point, so buckets stay small.