Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

K Closest Points to Origin

EasyPython00:00
Practice interviewer
In session
5 left
00:00

Your question is K Closest Points to Origin. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

In a Meta-style ranking or retrieval pipeline, you may need to quickly keep only the nearest candidate embeddings or coordinates. Given a list of points on a 2D plane, return the k points closest to the origin (0, 0).

The distance between a point (x, y) and the origin is sqrt(x^2 + y^2). For efficiency, compare points using squared distance x^2 + y^2 instead of computing square roots. You may return the answer in any order.

Formal Specification

  • Input:
    • points: a list of 2-element lists, where each element is [x, y]
    • k: an integer
  • Output:
    • A list containing exactly k points from points with the smallest distances to the origin

Constraints

  • 1 <= len(points) <= 10^4
  • -10^4 <= x, y <= 10^4
  • 1 <= k <= len(points)
  • Each point contains exactly two integers

Function Signature

def k_closest_points(points, k):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output