Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Top K Nearest Distances

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

Your question is Top K Nearest Distances. 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

Given an array of numeric distances distances, where each value represents the distance of one candidate vector from a query vector, return the indices of the k nearest neighbors in ascending order of distance. If two distances are equal, return the smaller index first. Write an optimized algorithm without using external libraries.

Constraints

  • 1 <= len(distances) <= 10^5
  • 0 <= distances[i] <= 10^9
  • 1 <= k <= len(distances)
  • Distances are finite numeric values

Function Signature

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