{"id":1031,"date":"2023-12-16T17:00:00","date_gmt":"2023-12-16T17:00:00","guid":{"rendered":"https:\/\/favtutor.com\/articles\/?p=1031"},"modified":"2023-12-18T05:22:49","modified_gmt":"2023-12-18T05:22:49","slug":"k-closest-points-to-origin","status":"publish","type":"post","link":"https:\/\/favtutor.com\/articles\/k-closest-points-to-origin\/","title":{"rendered":"Find K Closest Points to the Origin (C++, Java, Python)"},"content":{"rendered":"\n<p>K closest point is a classic coding problem that tells the nearest k points from the origin in a 2-D plane we are given n coordinates of a 2-D plane and we have to tell k points which are closest to the origin. In this article, we will see how to find k closest points to the origin using a heap. <\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>What is the K Closest Point to the Origin Problem?<\/strong><\/h2>\n\n\n\n<p><strong>In the K Closest Point to the Origin problem, we are given n number of coordinates of a 2-D plane and we have to tell the k nearest coordinates that are closest to the origin (0,0). The closest points are those whose Euclidean distance from the origin is minimal.<\/strong><\/p>\n\n\n\n<p>Let us understand it with an example, look at the following figure:<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img decoding=\"async\" width=\"1024\" height=\"489\" src=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/2-13-1024x489.png\" alt=\"Example of K Closest Point to the Origin\" class=\"wp-image-1033\" srcset=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/2-13-1024x489.png 1024w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/2-13-300x143.png 300w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/2-13-768x367.png 768w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/2-13-750x358.png 750w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/2-13-1140x544.png 1140w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/2-13.png 1276w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n\n\n<p>Here is the solution:<\/p>\n\n\n\n<p class=\"has-black-color has-text-color has-background\" style=\"background-color:#fedcba\">Points = [[2,3], [3,5], [-2,2]]<br>K = 2<br>Output = [-2, 2] [2, 3]\u00a0<\/p>\n\n\n\n<p>One way to solve this problem is to find the distance of all the points from the origin and store it in a data structure, let\u2019s say, vector. We will then sort the vector to get the closest distance first. We will iterate the vector till we get k closest points. We will also store the index of the original point along with the distance so that we can reach back to the point.<\/p>\n\n\n\n<p>The time complexity of the brute force technique is O(N log N), where N is the number of points, as we have to sort the vector which will be of size n.\u00a0The space complexity is O(N) for storing the elements in the vector.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Max-Heap to Find K Closest Points to the Origin<\/strong><\/h2>\n\n\n\n<p>In the max-heap approach to find K closest points to the origin, we will find the Euclidean distance of each point from the origin and store it in max-heap and maintain the size of the priority queue equal to k to store only k closest distance as size increases from k we will pop the highest distance present in the priority queue. By doing this, we will be reducing the space required from O(N) to O(k).<\/p>\n\n\n\n<p><strong>Euclidean distance = <\/strong>\u221a(x-0)<sup>2 <\/sup>+(y-0)<sup>2 <\/sup>Can be written as \u221a(x)<sup>2 <\/sup>+(y)<sup>2\u00a0 <\/sup>Because we are finding distance from origin<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img decoding=\"async\" width=\"1024\" height=\"471\" src=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/1-9-1024x471.png\" alt=\"Max-Heap Approach\" class=\"wp-image-1034\" srcset=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/1-9-1024x471.png 1024w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/1-9-300x138.png 300w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/1-9-768x353.png 768w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/1-9-750x345.png 750w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/1-9-1140x524.png 1140w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/1-9.png 1279w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n\n\n<p>Here are the steps to solve this problem using max-heap:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Firstly we will declare a priority queue (max-heap) where each element is a pair of distance and point.<\/li>\n\n\n\n<li>Now we will simply run a for loop on points array calculate Euclidean distance from each point and store it in our priority queue<\/li>\n\n\n\n<li>We will maintain the size of the priority queue as k so whenever the size is more than k we will run a condition and pop the highest element present in the priority queue&nbsp;<\/li>\n\n\n\n<li>At last, we are left with k elements in the priority queue which are our k closest points.<\/li>\n<\/ol>\n\n\n\n<p>Now, let&#8217;s move to the implementation!<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>C++ Code<\/strong><\/h3>\n\n\n\n<p>Below is the C++ program to find K closest points to the origin:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text\/x-c++src&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;C++&quot;,&quot;modeName&quot;:&quot;cpp&quot;}\">#include &lt;bits\/stdc++.h&gt;\n\nusing namespace std;\n\nvector&lt;vector&lt;int&gt;&gt; kClosest(vector&lt;vector&lt;int&gt;&gt;&amp; points, int k) {\n    vector&lt;vector&lt;int&gt;&gt; ans;\n    \n    \/\/ Create a max heap (priority queue) where each element is a pair of distance and point\n    priority_queue&lt;pair&lt;int, vector&lt;int&gt;&gt;&gt; maxHeap;\n\n    \/\/ Push points onto the heap, maintaining the size at most k\n    for (const auto&amp; point : points) {\n        int distance = point[0] * point[0] + point[1] * point[1];\n        maxHeap.push({distance, point});\n        if (maxHeap.size() &gt; k) {\n            maxHeap.pop();  \/\/ Keep the size of the heap at most k\n        }\n    }\n\n    \/\/ Pop elements from the heap and store them in the result\n    while (!maxHeap.empty()) {\n        ans.push_back(maxHeap.top().second);\n        maxHeap.pop();\n    }\n\n    \/\/ Reverse the result to get the closest points first\n    reverse(ans.begin(), ans.end());\n\n    return ans;\n}\n\nint main() {\n    \/\/ Example usage:\n    vector&lt;vector&lt;int&gt;&gt; points = {{2, 3}, {3, 5}, {-2, 2}};\n    int k = 2;\n\n    \/\/ Find the k closest points\n    vector&lt;vector&lt;int&gt;&gt; result = kClosest(points, k);\n\n    \/\/ Print the result\n    cout &lt;&lt; &quot;The &quot; &lt;&lt; k &lt;&lt; &quot; closest points are:\\n&quot;;\n    for (const auto&amp; point : result) {\n        cout &lt;&lt; &quot;[&quot; &lt;&lt; point[0] &lt;&lt; &quot;, &quot; &lt;&lt; point[1] &lt;&lt; &quot;] &quot;;\n    }\n\n    return 0;\n}<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Python Code<\/strong><\/h3>\n\n\n\n<p>Here is the Python program for this problem:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}\">import heapq\n\ndef k_closest(points, k):\n    ans = []\n    \n    # Create a max heap (priority queue) where each element is a pair of distance and point\n    max_heap = []\n\n    # Push points onto the heap, maintaining the size at most k\n    for point in points:\n        distance = point[0] ** 2 + point[1] ** 2\n        heapq.heappush(max_heap, (-distance, point))\n        if len(max_heap) &gt; k:\n            heapq.heappop(max_heap)  # Keep the size of the heap at most k\n\n    # Pop elements from the heap and store them in the result\n    while max_heap:\n        distance, point = heapq.heappop(max_heap)\n        ans.append(point)\n\n    # Reverse the result to get the closest points first\n    ans.reverse()\n\n    return ans\n\n# Example usage:\npoints = [[2, 3], [3, 5], [-2, 2]]\nk = 2\n\n# Find the k closest points\nresult = k_closest(points, k)\n\n# Print the result\nprint(&quot;The&quot;, k, &quot;closest points are:&quot;)\nfor point in result:\n    print(point)<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Java Code<\/strong><\/h3>\n\n\n\n<p>We have also Java in our arsenal:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text\/x-java&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Java&quot;,&quot;modeName&quot;:&quot;java&quot;}\">import java.util.*;\n\npublic class KClosestPoints {\n    public static List&lt;List&lt;Integer&gt;&gt; kClosest(int[][] points, int k) {\n        List&lt;List&lt;Integer&gt;&gt; ans = new ArrayList&lt;&gt;();\n        \n        \/\/ Create a max heap (priority queue) where each element is a pair of distance and point\n        PriorityQueue&lt;int[]&gt; maxHeap = new PriorityQueue&lt;&gt;((a, b) -&gt; Integer.compare(b[0], a[0]));\n\n        \/\/ Push points onto the heap, maintaining the size at most k\n        for (int[] point : points) {\n            int distance = point[0] * point[0] + point[1] * point[1];\n            maxHeap.offer(new int[]{distance, point[0], point[1]});\n            if (maxHeap.size() &gt; k) {\n                maxHeap.poll();  \/\/ Keep the size of the heap at most k\n            }\n        }\n\n        \/\/ Pop elements from the heap and store them in the result\n        while (!maxHeap.isEmpty()) {\n            int[] point = maxHeap.poll();\n            ans.add(Arrays.asList(point[1], point[2]));\n        }\n\n        \/\/ Reverse the result to get the closest points first\n        Collections.reverse(ans);\n\n        return ans;\n    }\n\n    public static void main(String[] args) {\n        \/\/ Example usage:\n        int[][] points = {{2, 3}, {3, 5}, {-2, 2}};\n        int k = 2;\n\n        \/\/ Find the k closest points\n        List&lt;List&lt;Integer&gt;&gt; result = kClosest(points, k);\n\n        \/\/ Print the result\n        System.out.println(&quot;The &quot; + k + &quot; closest points are:&quot;);\n        for (List&lt;Integer&gt; point : result) {\n            System.out.println(Arrays.toString(point.toArray()));\n        }\n    }\n}<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code>The 2 closest points are:\n&#91;-2, 2] &#91;2, 3]<\/code><\/pre>\n\n\n\n<p>The time complexity of the algorithm is O(N log K), where N is the number of points and K is the value of k. This complexity arises from the insertion and extraction operations on the priority queue.<\/p>\n\n\n\n<p>The space complexity is O(K) for storing the elements in the priority queue. As we are maintaining our priority queue for k elements only.<\/p>\n\n\n\n<p>You can learn more about <a href=\"https:\/\/favtutor.com\/blogs\/heap-in-python\" data-type=\"link\" data-id=\"https:\/\/favtutor.com\/blogs\/heap-in-python\">min and max heap<\/a> to better understand it.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Conclusion&nbsp;<\/strong><\/h2>\n\n\n\n<p>We have discussed the <a href=\"https:\/\/leetcode.com\/problems\/k-closest-points-to-origin\/\" data-type=\"link\" data-id=\"https:\/\/leetcode.com\/problems\/k-closest-points-to-origin\/\" target=\"_blank\" rel=\"noopener\">leetcode problem<\/a> of finding the k nearest points to the origin. We learned the max-heap approach to solve it efficiently with codes in C++, Python, and Java. Choosing the appropriate algorithm, and considering time and space complexities are crucial aspects when coding.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>K closest point is a classic coding problem that tells the nearest k points from the origin in a 2-D plane we are given n coordinates of a 2-D plane and we have to tell k points which are closest to the origin. In this article, we will see how to find k closest points [&hellip;]<\/p>\n","protected":false},"author":12,"featured_media":1037,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jnews-multi-image_gallery":[],"jnews_single_post":null,"jnews_primary_category":{"id":"","hide":""},"footnotes":""},"categories":[7],"tags":[14,15],"class_list":["post-1031","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-data-structures-algorithms","tag-dsa","tag-leetcode"],"_links":{"self":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1031","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/users\/12"}],"replies":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/comments?post=1031"}],"version-history":[{"count":3,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1031\/revisions"}],"predecessor-version":[{"id":1081,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1031\/revisions\/1081"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media\/1037"}],"wp:attachment":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media?parent=1031"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/categories?post=1031"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/tags?post=1031"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}