Closest Points to a Query Vector, Ranked with Index Tie-Break
Heaps, Sorting & SearchAuto-graded · 19 test casesLast updated
Select the k dataset points nearest to a query in n-dimensional space, ordered by distance, with ties resolved by smaller index.
You are given a reference point and a collection of other points, all living in the same n-dimensional space. Each point is a list of numeric coordinates, and every point has the same number of coordinates as the reference point.
Your task is to find which points in the collection are closest to the reference point under ordinary straight-line (Euclidean) distance, and report their positions.
The Euclidean distance between points p and q with n coordinates is the square root of the sum over all coordinates of (p[i] - q[i]) squared.
Task
Implement a function that receives:
target: the reference point, a list of numbers.k: how many points to return.points: a list of points, each a list of numbers with the same length astarget.
Return a list of k integers: the indices (0-based positions in points) of the k points closest to target.
Ordering rules
- The returned indices must be ordered from the closest point to the farthest of the selected points.
- If two points are exactly the same distance from
target, the one with the smaller index comes first. - This tie-break also decides which point is included when a tie straddles the cutoff at position
k. - A point identical to
targethas distance 0 and therefore ranks first (subject to the tie-break among other zero-distance points).
Constraints
1 <= k <= len(points)- All points, and
target, have the same dimension (at least 1). - Coordinates may be integers or floats, and may be negative.
- Duplicate points may appear in
points. - Return only indices, not the points themselves.
Examples
Example 1
Input: closest_point_indices([0, 0], 2, [[1, 0], [3, 4], [-1, 0], [0, 2]])
Output: [0, 2]
Example 2
Input: closest_point_indices([8, 9, 10], 3, [[10, 11, 12], [1, 2, 3], [4, 5, 6], [7, 8, 9], [13, 14, 15]])
Output: [3, 0, 2]
Example 3
Input: closest_point_indices([1, 2, 3], 1, [[1, 2, 3], [1, 2, 5], [0, 2, 3], [4, 5, 6]])
Output: [0]
Hints
Hint 1
Ranking by distance gives the same order as ranking by squared distance, because the square root never changes the order of non-negative numbers. You can skip the root entirely.
Hint 2
Attach the index to each candidate so that the sort key is the pair (squared distance, index). Comparing such pairs automatically applies the tie-break.
Hint 3
Once every index has its key, you only need the k smallest. You can sort everything and slice, or use a heap helper such as heapq.nsmallest, which already returns results in ascending order.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
- For every point, compute the squared Euclidean distance to
target: the sum of squared coordinate differences. - Give each index the key
(squared_distance, index). - Pick the
kindices with the smallest keys, in ascending key order.heapq.nsmallestdoes this directly.
Why it is correct
- The square root is strictly increasing on non-negative numbers, so ordering by squared distance is identical to ordering by true distance. Skipping the root also avoids false ties that could come from floating-point rounding of the root.
- Tuples compare lexicographically, so when two squared distances are equal the smaller index wins. Since indices are unique, every key is unique and the ordering is total and fully determined, which matches the required tie-break, including at the cutoff for
k. nsmallestreturns its result sorted by key ascending, which is exactly closest to farthest.
Complexity
With n points of dimension d:
- Time:
O(n*d + n log k). Each key costsO(d), and the size-kheap costsO(log k)per element. - Space:
O(k)beyond the input (the implementation may useO(n)whenkis close ton).
Reference solution
import heapq
from typing import List
def closest_point_indices(target: List[float], k: int, points: List[List[float]]) -> List[int]:
def sq_dist(i):
return sum((a - b) ** 2 for a, b in zip(target, points[i]))
return heapq.nsmallest(
k,
range(len(points)),
key=lambda i: (sq_dist(i), i),
)