K Closest Points to Origin
Try to solve the K Closest Points to Origin problem.
We'll cover the following
Statement
Given a list of points on a plane, where the plane is a 2-D array with (x, y) coordinates, find the closest points to the origin .
Note: Here, the distance between two points on a plane is the Euclidean distance:
Constraints:
-
k
points.length
-
x[i]
,y[i]
Examples
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
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
[[1, 3], [-2, 2], [5, -3]]
[[2, -1], [-2, 2], [1, 3]]
[[1, 3], [-2, 2], [2, -1]]
[[1, 3], [-2, 2], [3, -2]]
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.
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.
from point import Pointimport heapqdef k_closest(points, k):# Replace this placeholder return statement with your codereturn []