Find K Closest Points to the Origin

Given a list of points on the 2-D plane and an integer K. The task is to find K closest points to the origin and print them.

Note: The distance between two points on a plane is the Euclidean distance.

Examples:

Input : point = [[3, 3], [5, -1], [-2, 4]], K = 2
Output : [[3, 3], [-2, 4]]

Input : point = [[1, 3], [-2, 2]], K  = 1
Output : [[-2, 2]]


Approach :

  • Sort the points by distance using Euclidean distance formula.
  • Select first K points form the list
  • Print the points obtained in any order.

Consider two points with coordinates as (x1, y1) and (x2, y2) respectively. The euclidean distance between these two points will be:

√{(x2-x1)2 + (y2-y1)2}

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program for implementation of 
# above approach
  
# Function to return required answer
def pClosest(points, K):
  
    points.sort(key = lambda K: K[0]**2 + K[1]**2)
  
    return points[:K]
  
# Driver program
points = [[3, 3], [5, -1], [-2, 4]]
  
K = 2
  
print(pClosest(points, K))

chevron_right


Output:

[[3, 3], [-2, 4]]


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.