KD-Tree Exact K-Nearest-Neighbour Search
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: hard
Interview Round: Other
Implement `KDTree(X, leaf_size=1)` by recursively splitting at the median along the dimension of largest spread, stopping at nodes with at most `leaf_size` points. `query(Q, k)` returns `(distances, indices)`, each of shape `(m, k)`, with Euclidean distances in ascending order. Use a bounded max-heap of size `k` and skip a subtree when its splitting hyperplane is farther than the current k-th best. The tree also exposes an `n_distance_evals` counter, described under the constraints.
For example:
```python
X = [[0, -1], [2, 2], [-1, 0], [1, 0], [0, 1]]
KDTree(X).query([[0.0, 0.0]], 2)
# -> distances [[1.0, 1.0]], indices [[0, 2]] (tie -> lower index)
```
```hint Tie order
Points inside a leaf, and across subtrees, do not arrive in index order. Think about what the heap comparison has to include for the lower-index rule to hold.
```
```hint Pruning boundary
Consider a subtree whose hyperplane is exactly as far as the current k-th best. Could it still hold a point you must return?
```
```hint Points on the split
Values equal to the median can end up on either side of the split. Check that your lower bound still holds for them.
```
### Constraints & Assumptions
- Results must match brute force exactly. Equal distances (including duplicate points) are ordered by lower training index.
- `indices` dtype is `int64`. A 1-D `Q` is treated as a single query.
- `n_distance_evals` is reset at each `query` call and counts every point-to-query distance computed across all rows (with `k = n` it equals `n * m`).
- Pruning must be effective: for 2000 uniform 2-D points, `leaf_size=8`, `k=3`, evaluations stay below 10% of brute force.
- Raise `ValueError` for `k < 1` or `k > n`, a query dimension mismatch, empty or non-2-D `X`, or `leaf_size < 1`.
### What a Strong Answer Covers
- A build that chooses the split dimension by spread, splits at the median, and always terminates, including on duplicate points
- A pruning test that is a valid lower bound on distance and still lets equal-distance, lower-index points be found
- Heap ordering that reproduces brute-force output exactly, ties included
- Correct `n_distance_evals` accounting and every listed `ValueError` case
- Build and query complexity, and the conditions under which pruning stops paying off
### Follow-up Questions
- Why does KD-tree pruning degrade in high dimensions?
- How would you tighten pruning beyond the single-axis hyperplane test?
- How would you support a radius query instead of a fixed `k`?
Overview: Build a median-split KD-tree in Python with NumPy and answer exact k-nearest-neighbour queries using a bounded max-heap and hyperplane pruning. Tests tree construction, valid pruning bounds, tie-breaking that matches brute force, and how search cost changes with dimension.