KatInterview

Classify Queries by Nearest Reference After Linear Transform

Arrays & HashingAuto-graded · 14 test cases
HardAuto-gradedArrays & Hashingmatrix-operationsdistance-metricsvectorization

Last 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 X with shape (N, D_in)
  • A linear transformation defined by weight matrix W of shape (D_in, D_out) and bias vector b of shape (D_out,)
  • A reference database R of shape (M, D_out) containing pre-computed embeddings
  • Labels y_ref of shape (M,) corresponding to each reference embedding

Your task:

  1. Transform each query: compute E = X @ W + b to obtain embedded queries of shape (N, D_out), where @ denotes matrix multiplication
  2. Calculate the Euclidean distance from each embedded query to every reference embedding
  3. For each query, identify which reference embedding is closest (has minimum distance)
  4. If multiple references are equidistant from a query (within floating-point precision), select the one with the lowest index
  5. 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_ref are 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