KatInterview

Build a Bucketed Spatial Index for Planar Points

Data Structure DesignModel answer
MediumModel answerData Structure Designquadtreespatial-indexrecursion

Last 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: either null/None, or a list of four sub-rectangles (northwest, northeast, southwest, southeast).

Operations

  1. 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.
  2. 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.