DIY: K Closest Points to Origin

Solve the interview question "K Closest Points to Origin" in this lesson.

Problem statement

We have a list of points on the plane. Find the k closest points to the origin (0, 0).

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

Input

The input will be a list of points and a value k. The following is an example input:

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

Output

The output will be the k points from the points list that are closest to the origin. For the above input, the output will be:

[-2,2]

Coding exercise

For this coding exercise, you need to implement the function k_closest(points, k), where points is the list of multiple pairs of points in the form [x,y] and k represents the number of closest points that you have to find. The function will return the k points that are closest to the origin.

Level up your interview prep. Join Educative to access 80+ hands-on prep courses.