BackendML

K Closest Points to Origin

Medium3 min read
The K Closest Points to Origin problem requires finding the k points that are closest to the origin (0, 0) on a 2D plane.

Problem

Given an array of points where points[i] = [xi, yi] represents a point on a 2D plane, and an integer k, return the k points closest to the origin (0, 0).

The distance between a point (x, y) and the origin is calculated using the Euclidean distance. Since the square root does not affect the ordering, we can compare points using x2 + y2.

Example(s)

Consider the following examples to understand the expected input and output.

Example 1

Input
points = [[1,3],[-2,2]]
k = 1
Output
[[-2,2]]

Example 2

Input
points = [[3,3],[5,-1],[-2,4]]
k = 2
Output
[[3,3],[-2,4]]

Solution

Approach 1: Max Heap with Euclidean Distance

This solution uses a Max Heap to maintain the k closest points. The heap keeps the farthest point among the selected points at the root, allowing us to remove it whenever the heap size exceeds k.

We calculate the Euclidean distance from each point to the origin using Math.sqrt() and Math.pow(). Although this approach works correctly, these calculations are unnecessary because we only need to compare distances.
class Solution {
    public int[][] kClosest(int[][] points, int k) {
        PriorityQueue<int[]> maxHeap =
        new PriorityQueue<>((a, b) -> Double.compare(distance(b), distance(a)));

        for (int[] point : points) {
            maxHeap.offer(point);
            if (maxHeap.size() > k) {
                maxHeap.poll();
            }
        }

        int[][] result = new int[k][2];
        for (int i = 0; i < k; i++) {
            int[] point = maxHeap.poll();
            result[i][0] = point[0];
            result[i][1] = point[1];
        }

        return result;
    }

    private double distance(int[] point) {
        return Math.sqrt(Math.pow(point[0], 2) + Math.pow(point[1], 2));
    }
}

Approach 2: Max Heap with Squared Distance

We can optimize the previous approach by avoiding Math.sqrt() and Math.pow(). Since the square root function preserves the ordering of positive values, comparing x2 + y2 gives the same ordering as comparing the actual Euclidean distances.

Therefore, we calculate the squared distance directly and use it for the max heap comparison. This avoids unnecessary mathematical operations while producing the same result.
class Solution {
    public int[][] kClosest(int[][] points, int k) {
        PriorityQueue<int[]> maxHeap =
        new PriorityQueue<>((a, b) -> Integer.compare(distance(b), distance(a)));

        for (int[] point : points) {
            maxHeap.offer(point);
            if (maxHeap.size() > k) {
                maxHeap.poll();
            }
        }

        int[][] result = new int[k][2];
        for (int i = 0; i < k; i++) {
            result[i] = maxHeap.poll();
        }

        return result;
    }

    private int distance(int[] point) {
        return point[0] * point[0] + point[1] * point[1];
    }
}

Complexity

For both approaches, each point is inserted into a heap of size at most k. Therefore, the time complexity is O(n log k).

The max heap stores at most k points, so the extra space complexity is O(k).

The second approach is more optimized because it avoids Math.sqrt() and Math.pow() and directly compares squared distances.

Comments

No comments yet. Ask a question or share what helped.