We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

K Closest Points to Origin

Number: 1014

Difficulty: Medium

Paid? No

Companies: Meta, Amazon, Google, Salesforce, Asana, Apple, LinkedIn, Oracle, Wix


Problem Description

Given an array of points where each point is represented as [x, y], return the k closest points to the origin (0, 0) based on their Euclidean distance. The answer can be returned in any order.


Key Insights

  • Calculate the squared Euclidean distance (x² + y²) to avoid the overhead of square root computation.
  • Sorting the points based on their distance gives an O(n log n) solution.
  • Alternatively, using a max-heap to keep track of the k closest points results in O(n log k) time, which is effective if k is much smaller than n.
  • Using Quickselect can achieve an average time complexity of O(n), though the worst-case is O(n²).
  • The problem does not require the output to be sorted in any specific order.

Space and Time Complexity

Time Complexity: O(n log n) with a sorting approach, O(n log k) with a heap approach, or average O(n) with a Quickselect approach.
Space Complexity: O(n) if extra space is used for sorting, or O(k) for the heap approach.


Solution

We can solve this problem by first computing the squared Euclidean distance for each point to avoid unnecessary square root operations. Then, we can sort the points based on their computed distance and select the first k points.
Alternatively, a max-heap or Quickselect algorithm can be used:

  • Max-Heap: Maintain a heap of size k while iterating through the points, ensuring that only the k points with the smallest distances are kept.
  • Quickselect: Partition the array like in QuickSort to position the kth closest point in its correct position. Once partitioned, all points to the left of that position will be the k closest. The sorting solution is straightforward and efficient enough given the constraints.

Code Solutions

# Python Solution
def kClosest(points, k):
    # Sort the points based on their squared Euclidean distance from the origin.
    points.sort(key=lambda point: point[0]**2 + point[1]**2)
    # Return the first k points from the sorted list.
    return points[:k]

# Example usage:
# points = [[1,3], [-2,2]]
# k = 1
# print(kClosest(points, k))
← Back to All Questions