Implement a Tie-Aware KNN Classifier with Deterministic Distance and Vote Tie Policies

Quick Overview

Implement a k-nearest-neighbors classifier in NumPy whose neighbor order, boundary ties and vote ties are fully deterministic under configurable policies. Tests sorting with tiebreak keys, floating-point care at the boundary, input validation and probability normalization.

Implement a Tie-Aware KNN Classifier with Deterministic Distance and Vote Tie Policies

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: hard

Interview Round: Other

Implement a k-nearest-neighbors classifier `TieAwareKNN(k, boundary="truncate", vote_tie="smallest")` that uses Euclidean distance and exposes `fit(X, y)`, `kneighbors(X_query)`, `predict(X_query)` and `predict_proba(X_query)`. Neighbors are ordered by (distance, training index) ascending. Distance ties at the k-th neighbor and ties in the class vote must be resolved by the configured policies, so every result is deterministic. The `boundary` policy decides which neighbors are kept: - `"truncate"` keeps exactly `k` neighbors. - `"expand"` keeps every training point whose distance is at most the k-th distance. The `vote_tie` policy decides the label when several labels share the highest count: - `"smallest"` picks the smallest tied label. - `"nearest"` picks the tied label that appears first in neighbor order. - `"reduce_k"` drops the farthest neighbor (the last one in neighbor order) and votes again, repeating until one label wins. Examples. The first uses the default `boundary="truncate"`, and the second uses the default `vote_tie="smallest"`: ```text X = [[0], [1], [2], [3], [4], [5]]; y = [7, 3, 3, 7, 1, 1]; k = 6; query = [[0]] vote_tie="smallest" -> [1] vote_tie="nearest" -> [7] vote_tie="reduce_k" -> [3] # drop idx 5, 4, 3 -> label 3 wins X = [[0], [1], [-1], [2], [-2]]; y = [0, 1, 1, 0, 0]; k = 2; query = [[0]] truncate: proba [[0.5, 0.5]], predict [0] expand: proba [[1/3, 2/3]], predict [1] ``` ```hint Make every ordering total Sorting by distance alone leaves the order of equal distances up to the sort algorithm. Decide what breaks those ties and put it in the sort key. ``` ```hint Where boundary ties hide Look at the points just past the k-th one. Think about whether the boundary comparison should use distances or squared distances. ``` ```hint Probabilities under expand Under `"expand"` a query can keep more than `k` neighbors. Check what each probability row should be divided by. ``` ### Constraints & Assumptions - `kneighbors` returns `(dists, inds)`: two lists holding one 1-D array per query. Under `"expand"` the arrays can have different lengths. - `predict_proba` returns an array of shape `(n_queries, n_classes)`. Each entry is the label's count divided by the number of neighbors kept for that query, and the columns follow the sorted order of the training labels. - `predict` returns an array with the same dtype as `y`. - `__init__` raises `ValueError` when `k` is not an integer, when `k < 1`, or when either policy name is unknown. `fit` raises `ValueError` when `k` exceeds the number of training samples. ### Clarifying Questions to Ask - Are the labels always mutually comparable, so that "smallest" and the sorted column order are well defined? - Should an integer-valued float such as `3.0`, or a boolean, count as a valid `k`? - Should distance ties use exact equality on the computed values, or a tolerance? - Can the training data or the queries contain NaN or infinite values? ### What a Strong Answer Covers - A total neighbor order by (distance, training index), with the boundary comparison done on squared distances. - Both boundary policies, including the variable-length output under `"expand"`. - All three vote-tie policies, with an argument that `"reduce_k"` terminates. - `predict_proba` normalized by the actual neighbor count, and `predict` keeping the label dtype. - Input validation in `__init__` and `fit`, and the time complexity per query. ### Follow-up Questions - How would you add distance weighting without breaking determinism? - Why can floating-point error break tie detection, and how would you guard against it? - How would this scale to millions of training points?

Overview: Implement a k-nearest-neighbors classifier in NumPy whose neighbor order, boundary ties and vote ties are fully deterministic under configurable policies. Tests sorting with tiebreak keys, floating-point care at the boundary, input validation and probability normalization.

General logo
General
Nov 24, 2026
hardMachine Learning EngineerOtherMachine Learning
0
0

Implement a k-nearest-neighbors classifier TieAwareKNN(k, boundary="truncate", vote_tie="smallest") that uses Euclidean distance and exposes fit(X, y), kneighbors(X_query), predict(X_query) and predict_proba(X_query). Neighbors are ordered by (distance, training index) ascending. Distance ties at the k-th neighbor and ties in the class vote must be resolved by the configured policies, so every result is deterministic.

The boundary policy decides which neighbors are kept:

  • "truncate" keeps exactly k neighbors.
  • "expand" keeps every training point whose distance is at most the k-th distance.

The vote_tie policy decides the label when several labels share the highest count:

  • "smallest" picks the smallest tied label.
  • "nearest" picks the tied label that appears first in neighbor order.
  • "reduce_k" drops the farthest neighbor (the last one in neighbor order) and votes again, repeating until one label wins.

Examples. The first uses the default boundary="truncate", and the second uses the default vote_tie="smallest":

X = [[0], [1], [2], [3], [4], [5]]; y = [7, 3, 3, 7, 1, 1]; k = 6; query = [[0]]
vote_tie="smallest" -> [1]
vote_tie="nearest"  -> [7]
vote_tie="reduce_k" -> [3]   # drop idx 5, 4, 3 -> label 3 wins

X = [[0], [1], [-1], [2], [-2]]; y = [0, 1, 1, 0, 0]; k = 2; query = [[0]]
truncate: proba [[0.5, 0.5]],  predict [0]
expand:   proba [[1/3, 2/3]],  predict [1]

Constraints & Assumptions

  • kneighbors returns (dists, inds) : two lists holding one 1-D array per query. Under "expand" the arrays can have different lengths.
  • predict_proba returns an array of shape (n_queries, n_classes) . Each entry is the label's count divided by the number of neighbors kept for that query, and the columns follow the sorted order of the training labels.
  • predict returns an array with the same dtype as y .
  • __init__ raises ValueError when k is not an integer, when k < 1 , or when either policy name is unknown. fit raises ValueError when k exceeds the number of training samples.

Clarifying Questions to Ask Guidance

  • Are the labels always mutually comparable, so that "smallest" and the sorted column order are well defined?
  • Should an integer-valued float such as 3.0 , or a boolean, count as a valid k ?
  • Should distance ties use exact equality on the computed values, or a tolerance?
  • Can the training data or the queries contain NaN or infinite values?

What a Strong Answer Covers Guidance

  • A total neighbor order by (distance, training index), with the boundary comparison done on squared distances.
  • Both boundary policies, including the variable-length output under "expand" .
  • All three vote-tie policies, with an argument that "reduce_k" terminates.
  • predict_proba normalized by the actual neighbor count, and predict keeping the label dtype.
  • Input validation in __init__ and fit , and the time complexity per query.

Follow-up Questions Guidance

  • How would you add distance weighting without breaking determinism?
  • Why can floating-point error break tie detection, and how would you guard against it?
  • How would this scale to millions of training points?