K Closest Points to Origin
Explore how to find the k closest points to the origin in a 2D plane by applying heap data structures. Understand Euclidean distance calculation and implement top k selection techniques. This lesson helps you solve proximity problems commonly asked in coding interviews, building a foundation for advanced top k element challenges.
We'll cover the following...
Statement
You are given an array of points where each element points[i] k. Your task is to find and return the k points that are closest to the origin
The distance between two points on the X-Y plane is measured using Euclidean distance, which is calculated as:
Note: You can return the result in any order. The answer is guaranteed to be unique, except for the order in which points appear.
Constraints:
kpoints.length
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
(Select all that apply.) What is the output if the following data is given as an input?
points
k
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 the following coding playground.
public class Solution{public int[][] kClosest(int[][] points, int k) {// Replace this placeholder return statement with your codereturn new int[0][];}}