mlprep
Medium20 min·2 rounds

Implement k-nearest neighbors with efficient distance computation

Written by the mlprep team · Updated

Interviewer Mode
Interviewer

Implement k-nearest neighbors classification from scratch in NumPy. Focus on making the distance computation vectorized and efficient — no for loops over data points. Then discuss: what's the computational bottleneck and how would you address it at scale?

Ready to compare your reasoning?
Interviewer

Good. Now: your argpartition finds the k nearest neighbors, but then you do a Python loop for majority voting. Can you vectorize the majority vote too?

Ready to compare your reasoning?

The key takeaway unlocks after you reveal an expert answer.

Follow-up Questions to Test Yourself

Interviewers often pivot here once you cover the core concept.

  • How would you adapt this implementation to handle weighted features — where some dimensions matter more than others?
  • Explain the curse of dimensionality for KNN — why does KNN break down in high dimensions, and at what dimension count does this become a problem in practice?
  • How would you implement an online KNN that can add new training points without recomputing all distances?

How confident do you feel explaining this?

Track your understanding or flag it to revisit before your next loop.

Related Questions