K Closest Points to Origin
Detailed guide and Python implementation for the 'K Closest Points to Origin' problem.
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., 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]].
- •1 <= k <= len(points) <= 10^4
- •-10^4 <= xi, yi <= 10^4
Examples
points = [[1,3],[-2,2]], k = 1
[[-2,2]]
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.
points = [[3,3],[5,-1],[-2,4]], k = 2
[[3,3],[-2,4]]
The closest two points are (3, 3) and (-2, 4). (Order of elements in the output does not matter).
Need a Hint?
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.
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Generators
Learn how to use Python generators and yield statements to process huge datasets with minimal memory footprints. Master generator expressions.
How to Convert String to Int in Python
Learn how to convert a string to an integer in Python using the int() function. Handle errors safely and convert numbers from binary, octal, or hex.
Python Operators
Master arithmetic, comparison, logical, bitwise, assignment, and identity operators in Python.
Python Decorators vs Decorator Design Pattern: The Key Differences
Compare Python decorators and the classic decorator design pattern. Understand the differences between definition-time function wrapping and runtime dynamic object composition with runnable code.