K Closest Points to Origin

Medium · Heap & Counting · Array · Math · Divide and Conquer · Geometry · Sorting · Heap (Priority Queue) · Quickselect

Problem

You are given a list of points on a plane, each one [x, y], and an integer k. Return the k points closest to the origin (0, 0), measured by straight-line (Euclidean) distance, √(x² + y²).

The points may be returned in any order. The tests never have a tie for the last place, so the set of k points is always unique. A point listed twice is two points, and both can be in the answer.

Examples

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

(1, 3) is √10 from the origin and (-2, 2) is √8, so (-2, 2) is the closer one.

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

The squared distances are 18, 26 and 20. The two smallest are 18 and 20. [[-2,4],[3,3]] is also accepted.

Constraints

Approaches

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…