K Closest Points to Origin

Try to solve the K Closest Points to Origin problem.

Statement

Given a list of points on a plane, where the plane is a 2-D array with (x, y) coordinates, find the kk closest points to the origin (0,0)(0, 0).

Note: Here, the distance between two points on a plane is the Euclidean distance: x2+y2 \sqrt{x^2 + y^2}

Constraints:

  • 11 \leq k \leq points.length 103\leq 10^3
  • 104<-10^4 < x[i], y[i]<104< 10^4

Examples

1 of 4

Understand the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

K Closest Points to Origin

1

What is the output if the following list of points and value of k is given as input?

Select all that apply.

points = [[1, 3], [-2, 4], [2, -1], [-2, 2], [5, -3], [3, -2]]

k = 3

A)

[[1, 3], [-2, 2], [5, -3]]

B)

[[2, -1], [-2, 2], [1, 3]]

C)

[[1, 3], [-2, 2], [2, -1]]

D)

[[1, 3], [-2, 2], [3, -2]]

Question 1 of 40 attempted

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Drag and drop the cards to rearrange them in the correct sequence.

Try it yourself

Implement your solution in main.py and point.py in the following coding playground.

A Point class has two data members, x and y coordinates. You may add members or methods to it to support your solution.

Note: The order of the points returned is not significant.

Press + to interact
Python
usercode > main.py
from point import Point
import heapq
def k_closest(points, k):
# Replace this placeholder return statement with your code
return []
K Closest Points to Origin