Open In App

# K Closest Points to a given Target point

Given a list of points on the 2-D plane arr[][], a given point target, and an integer K. The task is to find K closest points to the target from the given list of points.

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

Examples:

Input: points = [[3, 3], [5, -1], [-2, 4]], target = [0, 0], K = 2
Output: [[3, 3], [-2, 4]]
Explanation: Square of Distance of target(=origin) from this point is
(3, 3) = 18
(5, -1) = 26
(-2, 4) = 20
So the closest two points are [3, 3], [-2, 4].

Input: points = [[1, 3], [-2, 2]], target = [0, 1], K  = 1
Output: [[1, 3]]

Approach: The solution is based on Greedy approach. The idea is to calculate the Euclidean distance from the target for every given point and store them in an array. Then sort the array according to the Euclidean distance found and print the first k closest points from the list.

Below is the implementation of above approach.

## C++

 `// C++ program to implement of above approach``#include ``using` `namespace` `std;` `// Calculate the Euclidean distance``// between two points``float` `distance(``int` `x1, ``int` `y1, ``int` `x2, ``int` `y2)``{``    ``return` `sqrt``(``pow``((x1 - x2), 2) +``                ``pow``((y1 - y2), 2));``}` `// Function to calculate K closest points``vector > kClosest(``    ``vector >& points,``    ``vector<``int``> target, ``int` `K)``{` `    ``vector > pts;``    ``int` `n = points.size();``    ``vector > d;` `    ``for` `(``int` `i = 0; i < n; i++) {``        ``d.push_back(``            ``make_pair(distance(points[i][0], points[i][1],``                               ``target[0], target[1]),``                      ``i));``    ``}` `    ``sort(d.begin(), d.end());` `    ``for` `(``int` `i = 0; i < K; i++) {``        ``vector<``int``> pt;``        ``pt.push_back(points[d[i].second][0]);``        ``pt.push_back(points[d[i].second][1]);``        ``pts.push_back(pt);``    ``}` `    ``return` `pts;``}` `// Driver code``int` `main()``{``    ``vector > points``        ``= { { 1, 3 }, { -2, 2 } };``    ``vector<``int``> target = { 0, 1 };``    ``int` `K = 1;` `    ``for` `(``auto` `pt : kClosest(points, target, K)) {``        ``cout << pt[0] << ``" "` `<< pt[1] << endl;``    ``}``    ``return` `0;``}`

## Java

 `// Java program to implement of above approach``import` `java.util.*;` `class` `GFG{``    ``static` `class` `pair``    ``{``        ``float` `first;``        ``float` `second;``        ``public` `pair(``float` `f, ``float` `second) ``        ``{``            ``this``.first = f;``            ``this``.second = second;``        ``}   ``    ``}``  ` `// Calculate the Euclidean distance``// between two points``static` `float` `distance(``int` `x1, ``int` `y1, ``int` `x2, ``int` `y2)``{``    ``return` `(``float``) Math.sqrt(Math.pow((x1 - x2), ``2``) +``                ``Math.pow((y1 - y2), ``2``));``}` `// Function to calculate K closest points``static` `Vector > kClosest(``    ``int``[][] points,``    ``int``[] target, ``int` `K)``{` `    ``Vector> pts = ``new` `Vector>();``    ``int` `n = points.length;``    ``Vector d = ``new` `Vector();` `    ``for` `(``int` `i = ``0``; i < n; i++) {``        ``d.add(``            ``new` `pair(distance(points[i][``0``], points[i][``1``],``                               ``target[``0``], target[``1``]),``                      ``i));``    ``}``    ``Collections.sort(d, (a, b) -> (``int``)(a.first - b.first));``  `  `    ``for` `(``int` `i = ``0``; i < K; i++) {``        ``Vector pt = ``new` `Vector();``        ``pt.add(points[(``int``) d.get(i).second][``0``]);``        ``pt.add(points[(``int``) d.get(i).second][``1``]);``        ``pts.add(pt);``    ``}` `    ``return` `pts;``}` `// Driver code``public` `static` `void` `main(String[] args)``{``    ``int``[][] points``        ``= { { ``1``, ``3` `}, { -``2``, ``2` `} };``    ``int``[] target = { ``0``, ``1` `};``    ``int` `K = ``1``;` `    ``for` `(Vector  pt : kClosest(points, target, K)) {``        ``System.out.print(pt.get(``0``)+ ``" "` `+  pt.get(``1``) +``"\n"``);``    ``}``}``}` `// This code is contributed by 29AjayKumar`

## Python3

 `# Python code for the above approach` `# Calculate the Euclidean distance``# between two points``def` `distance(x1, y1, x2, y2):``    ``return` `((x1 ``-` `x2) ``*``*` `2` `+` `(y1 ``-` `y2) ``*``*` `2``) ``*``*` `( ``1` `/` `2``)` `# Function to calculate K closest points``def` `kClosest(points, target, K):``    ``pts ``=` `[]``    ``n ``=` `len``(points)``    ``d ``=` `[]` `    ``for` `i ``in` `range``(n):``        ``d.append({``            ``"first"``: distance(points[i][``0``], points[i][``1``], target[``0``], target[``1``]),``            ``"second"``: i``        ``})``    ` `    ``d ``=` `sorted``(d, key``=``lambda` `l:l[``"first"``])` `    ``for` `i ``in` `range``(K):``        ``pt ``=` `[]``        ``pt.append(points[d[i][``"second"``]][``0``])``        ``pt.append(points[d[i][``"second"``]][``1``])``        ``pts.append(pt)` `    ``return` `pts` `# Driver code``points ``=` `[[``1``, ``3``], [``-``2``, ``2``]]``target ``=` `[``0``, ``1``]``K ``=` `1` `for` `pt ``in` `kClosest(points, target, K):``    ``print``(f``"{pt[0]} {pt[1]}"``)` `# This code is contributed by gfgking.`

## C#

 `// C# program to implement of above approach``using` `System;``using` `System.Collections.Generic;` `public` `class` `GFG {``    ``public` `class` `pair {``        ``public` `float` `first;``        ``public` `float` `second;` `        ``public` `pair(``float` `f, ``float` `second) {``            ``this``.first = f;``            ``this``.second = second;``        ``}``    ``}` `    ``// Calculate the Euclidean distance``    ``// between two points``    ``static` `float` `distance(``int` `x1, ``int` `y1,``                          ``int` `x2, ``int` `y2)``    ``{``        ``return` `(``float``) Math.Sqrt(Math.Pow((x1 - x2), 2) +``                                 ``Math.Pow((y1 - y2), 2));``    ``}` `    ``// Function to calculate K closest points``    ``static` `List> kClosest(``int``[,] points,``                                    ``int``[] target, ``int` `K)``    ``{` `        ``List> pts = ``new` `List>();``        ``int` `n = points.GetLength(0);``        ``List d = ``new` `List();` `        ``for` `(``int` `i = 0; i < n; i++) {``            ``d.Add(``new` `pair(distance(points[i,0], points[i,1],``                                    ``target[0], target[1]), i));``        ``}` `        ``for` `(``int` `i = 0; i < K; i++) {``            ``List<``int``> pt = ``new` `List<``int``>();``            ``pt.Add(points[(``int``) d[i].second,0]);``            ``pt.Add(points[(``int``) d[i].second,1]);``            ``pts.Add(pt);``        ``}` `        ``return` `pts;``    ``}` `    ``// Driver code``    ``public` `static` `void` `Main(String[] args) {``        ``int``[,] points = { { 1, 3 }, { -2, 2 } };``        ``int``[] target = { 0, 1 };``        ``int` `K = 1;` `        ``foreach` `(List<``int``> pt ``in` `kClosest(points, target, K))``        ``{``            ``Console.Write(pt[0] + ``" "` `+ pt[1] + ``"\n"``);``        ``}``    ``}``}` `// This code is contributed by Rajput-Ji`

## Javascript

 ``

Output

`1 3`

Time Complexity: O(N * logN)
Auxiliary Space: O(N)