Ball Tree With Exact k-NN Queries
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: hard
Interview Round: Other
Implement a class `BallTree(X, leaf_size=2)` that builds a ball tree over training points `X` of shape `(n, d)`, and a method `query(Q, k=1)` that returns `(dists, inds)`: two arrays of shape `(m, k)` holding the exact Euclidean k nearest neighbors of each query row, sorted by ascending `(distance, index)`.
Requirements:
- Build recursively in pre-order (root = node 0). A node with at most `leaf_size` points is a leaf (`node_left` = `node_right` = `-1`).
- Split on the dimension with the largest `max - min` (lowest dimension on ties), sorting by that coordinate and then by training index. The left child gets the first `len // 2` points.
- Each node owns the contiguous slice `idx_array[node_start:node_end]`. Store `centroids` (the mean of the node's points) and `radii` (the largest distance from a node point to its centroid).
- Prune nodes whose lower bound exceeds the current k-th distance, and visit the child with the closer centroid first.
- Each call to `query` resets `n_distance_evaluations` and counts only the point distances computed in leaves.
- Raise `ValueError` for an empty or non-2D `X`, for `leaf_size < 1`, or for `k` outside `[1, n]`.
Example:
```python
X = [[0, 0], [10, 1], [2, 5], [9, 9], [1, 1]]
t = BallTree(X, leaf_size=2)
t.idx_array # [0, 4, 2, 3, 1]
t.node_start # [0, 0, 2, 2, 3]
t.node_end # [5, 2, 5, 3, 5]
t.node_left # [1, -1, 3, -1, -1]
t.node_right # [2, -1, 4, -1, -1]
t.centroids[0] # [4.4, 3.2]
t.radii[0] # sqrt(54.8)
X = [[1, 0], [0, 1], [-1, 0], [0, -1], [0, 0]]
BallTree(X).query([[0, 0]], k=3)
# (array([[0., 1., 1.]]), array([[4, 0, 1]]))
```
In the second example four points tie at distance 1, so indices 0 and 1 win over 2 and 3.
```hint Numbering the nodes
Node ids come out in pre-order only if a node takes its slot in the arrays before either child is built.
```
```hint A bound for a whole ball
For a ball with center c and radius r, ask how close any point inside it can possibly be to the query q.
```
```hint Matching brute force on ties
Compare candidates as (distance, index) pairs everywhere, and think about what floating-point rounding can do to a pruning test that sits exactly on the boundary.
```
### Constraints & Assumptions
- `X` has shape `(n, d)` with `n >= 1` and `d >= 1`. Each query batch `Q` has shape `(m, d)`.
- `leaf_size` is an integer, at least 1, default 2. `k` is an integer with `1 <= k <= n`.
- Distance is Euclidean.
- Only `numpy` and the standard library are needed.
- Results must equal a brute-force search exactly, including the order of tied neighbors.
### What a Strong Answer Covers
- A build that reproduces the exact node arrays: pre-order ids, the split dimension and its tie rule, the coordinate-then-index sort, and the `len // 2` split.
- A pruning bound derived from the triangle inequality, with an argument that it never discards a true neighbor.
- Tie handling that matches brute force: `(distance, index)` comparisons, a strict pruning test, and protection against rounding error.
- The bookkeeping the spec asks for: the distance counter, input validation, and output shapes and order.
- Build and query cost, and how query cost changes as the dimension grows.
### Follow-up Questions
- Why is `dist(q, centroid) - radius` a valid pruning bound?
- When would you prefer a ball tree over a KD-tree or brute force?
- How would you add a radius query, or answer many queries at once efficiently?
Overview: Implement a ball tree in Python and numpy that stores its nodes in flat pre-order arrays and answers exact Euclidean k-nearest-neighbor queries. It tests triangle-inequality pruning, branch-and-bound search, and tie-breaking by index that matches a brute-force scan.