Parameterised Minkowski Distance for KNN
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement `minkowski_distance(a, b, p=2.0)` returning the distance $\left(\sum_i |a_i - b_i|^p\right)^{1/p}$ as a `float`, with `p=np.inf` giving $\max_i |a_i - b_i|$ (Chebyshev). Implement `pairwise_minkowski(X, Y, p=2.0)` returning the `(n_X, n_Y)` distance matrix between rows, and `k_nearest_neighbors(X_train, query, k, p=2.0)` returning `(indices, distances)` of the `k` closest training rows, sorted ascending by distance.
For example:
```python
minkowski_distance([0, 0], [3, -4], 1) # 7.0
minkowski_distance([0, 0], [3, -4], 2) # 5.0
minkowski_distance([0, 0], [3, -4], np.inf) # 4.0
X_train = [[1, 0], [0, 1], [-1, 0], [0, 0.5], [3, 3]]
k_nearest_neighbors(X_train, [0, 0], 3, 2)
# (array([3, 0, 1]), array([0.5, 1.0, 1.0]))
```
```hint One reduction for every p
All three functions need the same step: absolute coordinate differences reduced over the feature axis. Write that step once, then ask which value of p needs a different operation from the others.
```
```hint Ties
Several training rows can sit at exactly the same distance from the query. Check whether the sort you use keeps equal keys in their original order.
```
### Constraints & Assumptions
- `p` must be at least 1 or `np.inf`, otherwise raise `ValueError` (all three functions).
- Mismatched vector lengths or feature dimensions raise `ValueError`.
- `k` outside `[1, n_train]` raises `ValueError`.
- Equal distances break ties by lower training index.
- Results must match `scipy.spatial.distance.cdist` to a relative tolerance of `1e-7`.
### What a Strong Answer Covers
- Validation of `p`, including `np.inf`, NaN and values below 1, with the reason p below 1 is rejected
- One difference-and-reduce step shared by the scalar and matrix functions, with the infinity case handled on its own
- Broadcasting to build the pairwise matrix, and the memory that costs
- A neighbor selection that breaks ties by training index every time
- Time and space complexity for the pairwise matrix and for a single query
### Follow-up Questions
- The broadcast difference tensor needs $O(n_X \cdot n_Y \cdot d)$ memory. How would you compute the matrix for 100,000 query rows against 1,000,000 training rows?
- For a large p such as 100, $|a_i - b_i|^p$ overflows for fairly small differences. How would you rewrite the general case so it stays finite?
- How would you find the k nearest rows faster than a full sort and still break ties by index?
- What goes wrong in a kNN model if you allow p = 0.5?
Overview: Asks for NumPy implementations of the Minkowski distance for any p of at least 1 or infinity, a pairwise distance matrix built with broadcasting, and a k-nearest-neighbor lookup. Tests input validation, the Chebyshev limit case and deterministic tie-breaking by training index.