December 17, 2021

K Closest Points to Origin

Problem Statement: Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0).

The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2).

You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in).


Example 1:

Input: points = [[1,3],[-2,2]], k = 1
Output: [[-2,2]]
Explanation:
The distance between (1, 3) and the origin is sqrt(10).
The distance between (-2, 2) and the origin is sqrt(8).
Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.
We only want the closest k = 1 points from the origin, so the answer is just [[-2,2]].


Constraints:

  • 1 <= k <= points.length <= 104
  • -104 < xi, yi < 104


Leetcode Difficulty: Medium

Code:
    def get_distance(self, point):
        origin=[0,0]
        return ((point[1]-origin[1])**2 + (point[0]-origin[0])**2)**0.5
    
    def kclosest(self, points, k):
        """
        points: List[List[int]]
        k: int
        return: List[List[int]]
        """
        
        heap=[]
        for point in points[:k]:
            distance = self.get_distance(point)
            heapq.heappush(heap, (-1*distance,point))
        
        for point in points[k:]:
            distance = -1*self.get_distance(point)
            
            top = heapq.heappop(heap)
            
            if top[0]<distance:
                heapq.heappush(heap, (distance,point))
            else:
                heapq.heappush(heap, top)
        
        return [heapq.heappop(heap)[1] for _ in range(k)]

Thought Process / Explanation:
The keyword "k closest" hints me to give a shot to heaps. Since heapq implements min-heap by default. We multiply the distance by -1 to make sure the absolute largest is on top every time (acting as max-heap). The rest is just a comparison from the top and updating things.



Thank You!

No comments:

Post a Comment

Please share your valuable feedback. It will help me and community grow.