Leetcode 973: K Closest Points to Origin

grid47
grid47
Exploring patterns and algorithms
Aug 1, 2024 4 min read

Given an array of points on a 2D plane, find the k closest points to the origin (0, 0) based on Euclidean distance. If multiple points have the same distance, any order is acceptable.
Problem
Approach
Steps
Complexity
Input: An array of points on the X-Y plane and an integer k.
Example: points = [[2, -1], [1, 2], [-3, -4]], k = 2
Constraints:
• 1 <= k <= points.length <= 10^4
• -10^4 <= xi, yi <= 10^4
Output: An array of k points that are closest to the origin.
Example: [[1, 2], [2, -1]]
Constraints:
• The answer may be returned in any order.
Goal: Identify the k points with the smallest Euclidean distances from the origin.
Steps:
• Calculate the Euclidean distance for each point from the origin.
• Sort the points by distance in ascending order.
• Return the first k points.
Goal: Ensure the inputs adhere to the problem's constraints.
Steps:
• 1 <= k <= points.length <= 10^4
• -10^4 <= xi, yi <= 10^4
Assumptions:
• The input points array is valid and non-empty.
• The integer k is always less than or equal to the length of the points array.
Input: points = [[-1, -1], [2, 2], [4, 5]], k = 1
Explanation: The closest point is [-1, -1] because it has the smallest Euclidean distance to the origin.

Input: points = [[2, -1], [1, 2], [-3, -4]], k = 2
Explanation: The two closest points are [1, 2] and [2, -1] because their distances are smaller than [-3, -4].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus