KatInterview

Closest Points to a Query Vector, Ranked with Index Tie-Break

Heaps, Sorting & SearchAuto-graded · 19 test cases
EasyAuto-gradedHeaps, Sorting & Searchk-nearest-neighborssortingheap

Last 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 as target.

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 target has 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.