K Closest Points to Origin

Medium#973k largest

You get points on a plane as pairs (x, y) and a number k. Return the k points closest to the origin (0, 0), in any order; the answer is always unique. Our example: (2, 2), (-3, 1), (1, 0), (0, -4), (-1, -2), (3, 3) and k = 3 — the answer is (2, 2), (1, 0) and (-1, -2).

input
points: points on a plane, each [x, y]; k: how many to return.
returns
The k points closest to the origin (0, 0), in any order. The answer is always unique.
constraints
  • 1 ≤ k ≤ points.length ≤ 10⁴
  • −10⁴ ≤ xᵢ, yᵢ ≤ 10⁴
  • the answer is unique
our 11 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[][]} points
 * @param {number} k
 * @return {number[][]}
 */
function kClosest(points, k) {

}
Ctrl ↵
format
reset

saved in this browser

11 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more heap and top k problems

Pattern “Heap and top K” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.