Back to Practice Dashboard
Top 150 InterviewEasy

K Closest Points to Origin

Learn how to solve the 'K Closest Points to Origin' problem. This detailed resource details brute force and optimized approaches.

Problem Statement

Easy

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., sqrt((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).

Write a function kClosest(points: List[List[int]], k: int) -> List[List[int]].

Constraints
  • 1 <= k <= len(points) <= 10^4
  • -10^4 <= xi, yi <= 10^4

Examples

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

The distance from (1, 3) to the origin is sqrt(10). The distance from (-2, 2) to the origin is sqrt(8). Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.

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

The closest two points are (3, 3) and (-2, 4). (Order of elements in the output does not matter).

Need a Hint?
Analyze the input constraints. Try sorting first (O(n log n)) or using a hash map/set to track seen elements in O(n) time.
Edge Cases to Watch
  • Empty list or null input variables
  • Single item lists/arrays
  • Extremely large input bounds causing integer or stack overflow

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor