All problems
MediumRetrieval & Rankingv2026-06-30

Retrieval & Ranking ยท Medium

Brute-Force Nearest Neighbor

Find exact nearest neighbors by exhaustively ranking Euclidean distances.

Task

Implement brute_force_nearest_neighbor(points: list[list[float]], queries: list[list[float]], k: int) -> tuple[list[list[int]], list[list[float]]]. Find the k nearest stored points for every query by exhaustively computing Euclidean distances.

Requirements

  • points is a non-empty rectangular matrix, queries is a rectangular matrix, and every point and query has the same positive feature dimension.
  • All coordinates are finite numeric values and k is a non-negative integer.
  • Process every query independently and compare it with every stored point.
  • Rank neighbors by ascending Euclidean distance; when distances tie, rank the smaller original point index first.
  • For each query, return at most min(k, len(points)) neighbors.
  • Return a pair (indices, distances), where each indices row contains original point indices and the matching distances row contains their Euclidean distances in rank order.
  • When k is zero, return one empty indices row and one empty distances row per query.
  • When k is at least the number of stored points, return every point in deterministic rank order.
  • Return two empty outer lists when queries is empty, and do not mutate either input.

Example

brute_force_nearest_neighbor(
    [[0.0, 0.0], [2.0, 0.0], [1.0, 1.0], [4.0, 0.0]],
    [[1.0, 0.0], [3.0, 0.0]],
    2,
)
# ([[0, 1], [1, 3]], [[1.0, 1.0], [1.0, 1.0]])
solution.pySign in to save
Public tests run locally in your browser.
Run your code to see public test results.