InferenceAI

Enter at least two characters to search.

Start free

K Closest Points

mediumHeaps25 min25 XP

Return the k points closest to the origin by Euclidean distance x2+y2\sqrt{x^2 + y^2}. Return them sorted by distance, breaking ties by xx then yy.

Requirements

  • Compare squared distances to avoid square roots.

Examples

EXAMPLE WALKTHROUGHone point

A guided view of the published example, not a trace of your code.

INPUT[[[1,3],[-2,2]],1]
TASKclosest_points()
EXPECTED OUTPUT[[-2,2]]

Start with the input values shown in this example.

Example 1 of 3

Input: points = [[1,3],[-2,2]], k = 1

Output: [[-2,2]]

Explanation: one point

Input: points = [[3,3],[5,-1],[-2,4]], k = 2

Output: [[3,3],[-2,4]]

Explanation: two points

Input: points = [[0,1],[1,0]], k = 2

Output: [[0,1],[1,0]]

Explanation: tie

Hint 1

heapq.nsmallest with a key works in O(n log k).

Topics

DSAHeapsPython