Classify Queries by Nearest Reference After Linear Transform
Arrays & HashingAuto-graded · 14 test casesLast updated
Tests vectorized linear projection, pairwise distance computation, and nearest-neighbor selection with tie-breaking.
Problem Statement
You are building a classification system that transforms input features through a linear layer and assigns labels by finding the closest match in a reference database.
Given:
- A batch of query vectors
Xwith shape(N, D_in) - A linear transformation defined by weight matrix
Wof shape(D_in, D_out)and bias vectorbof shape(D_out,) - A reference database
Rof shape(M, D_out)containing pre-computed embeddings - Labels
y_refof shape(M,)corresponding to each reference embedding
Your task:
- Transform each query: compute
E = X @ W + bto obtain embedded queries of shape(N, D_out), where@denotes matrix multiplication - Calculate the Euclidean distance from each embedded query to every reference embedding
- For each query, identify which reference embedding is closest (has minimum distance)
- If multiple references are equidistant from a query (within floating-point precision), select the one with the lowest index
- Return two lists: the predicted labels (one per query) and the Euclidean distances to the nearest neighbors
Euclidean distance between vectors u and v is defined as:
sqrt(sum((u[i] - v[i])^2 for i in range(len(u))))
Tie-breaking rule: When computing the minimum distance, if reference i and reference j (where i < j) have distances that differ by less than floating-point epsilon from a query, choose reference i.
Implementation note: While an optimal solution would use vectorized operations, any correct implementation that produces the expected output is acceptable. The reference solution processes queries one at a time using standard Python loops and list comprehensions.
Constraints
1 ≤ N ≤ 5,000(number of queries)1 ≤ M ≤ 20,000(number of references)1 ≤ D_in ≤ 512(input dimension)1 ≤ D_out ≤ 256(embedding dimension)- All input lists contain floating-point numbers
- Labels in
y_refare integers - Floating-point arithmetic may introduce small numerical errors; handle them by clamping negative squared distances to 0.0 before taking the square root
Examples
Example 1
Input: nearest_neighbor_classify([[1, 2]], [[1, 0], [0, 1]], [0, 0], [[1, 1], [4, 6]], [10, 20])
Output: [[10], [1]]
Example 2
Input: nearest_neighbor_classify([[0]], [[1]], [0], [[-2], [2]], [100, 200])
Output: [[100], [2]]
Hints
Hint 1
Start by computing the embedding for each query: multiply by W and add b
Hint 2
For each embedded query, compute its squared distance to every reference, then find the minimum
Hint 3
When comparing distances to find the minimum, iterate through references in order so ties naturally resolve to the lowest index
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution processes each query in three steps:
1. Linear Transformation
For each query vector, apply the linear transformation to produce an embedding. For output dimension j, compute:
embedding[j] = sum(query[k] * W[k][j] for k in range(D_in)) + b[j]
This maps the query from input space into the embedding space where comparisons with references take place.
2. Distance Computation For the embedded query, compute its squared Euclidean distance to each reference:
squared_distance = sum((embedding[j] - reference[j])^2 for j in range(D_out))
Working with squared distances avoids computing square roots until the final step, which is more efficient.
3. Nearest Neighbor Selection
Scan through all references in order, tracking the index with the smallest squared distance. Use strict inequality (< not <=) when comparing distances, so that when two references are equidistant, the earlier one is kept. This implements the required tie-breaking by lowest index.
After identifying the winner, take the square root of the best squared distance to get the actual Euclidean distance. Clamp negative values to zero first to handle floating-point rounding errors.
Why This Works
- Minimizing squared distance is equivalent to minimizing distance because square root is a monotonically increasing function
- Processing references in index order and using strict inequality for updates ensures ties resolve to the lowest index
- Deferring the square root operation until after finding the minimum avoids redundant computation
Complexity
- Time: O(N × D_in × D_out) for computing embeddings plus O(N × M × D_out) for distance computations. The second term dominates when M is large.
- Space: O(D_out) for the embedding of a single query at a time, plus O(1) auxiliary space.
Edge Cases
- Single query or single reference: the loops handle these naturally
- All references equidistant: the first one (index 0) is selected
- Query exactly matches a reference: squared distance is 0.0, final distance is 0.0
- Floating-point errors producing tiny negative squared distances: the
max(0.0, ...)clamp prevents NaN from sqrt
Solution
from math import sqrt
from typing import List
def nearest_neighbor_classify(X, W, b, R, y_ref):
predictions = []
distances = []
for x in X:
# Step 1: Compute embedding via linear transformation
embedding = [sum(x[k] * W[k][j] for k in range(len(W))) + b[j]
for j in range(len(b))]
# Step 2-3: Find the nearest reference by scanning all candidates
best_index = 0
best_squared_distance = float("inf")
for i, reference in enumerate(R):
squared_distance = sum((embedding[j] - reference[j]) ** 2
for j in range(len(embedding)))
# Strict inequality ensures lowest-index wins on ties
if squared_distance < best_squared_distance:
best_index = i
best_squared_distance = squared_distance
# Record the label and distance for this query
predictions.append(y_ref[best_index])
distances.append(sqrt(max(0.0, best_squared_distance)))
return predictions, distances