Top 150 InterviewEasy

K Closest Points to Origin

Detailed guide and Python implementation for the 'K Closest Points to Origin' problem.

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?
Consider using Heap / Priority Queue-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Ready to Solve?

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

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.