Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

CODING CHALLENGE · N°11

K-Nearest Neighbors

Medium AI EngineeringMachine LearningClassification

The simplest classifier there is: to label a new point, look at the k closest labeled points and let them vote. No training, no weights — just distances. The whole model is the dataset. No numpy, just the math.

The problem

Implement k-nearest-neighbors classification. You are given points (a list of training feature vectors), labels (the integer class of each training point), a query vector, and an integer k. Measure the Euclidean distance from the query to every training point, take the k closest, and return the majority label among them. Tie-breaks (both deterministic): when two points are equidistant, prefer the one that appears earlier in points; when two labels are tied on votes, return the smaller label.

SOLVE IT YOURSELF

Your turn — write it

Edit the stub, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? open the hints under the problem, or Reveal solution is one click away.

YOUR TASK

Implement knn(points, labels, query, k). Find the k training points closest to the query by Euclidean distance, then return the majority label (smaller label wins a vote tie).

CPython · WebAssembly
Examples and constraints 4 examples
EXAMPLE 1
Input points=[[0,0],[10,10]], labels=[0,1], query=[1,1], k=1
Output 0
k=1 → just the single nearest point
EXAMPLE 2
Input points=[[0,0],[0,1],[1,0],[10,10],[10,11],[11,10]], labels=[0,0,0,1,1,1], query=[0.5,0.5], k=3
Output 0
the three nearest all belong to cluster 0
EXAMPLE 3
Input points=[[0,0],[2,0]], labels=[1,0], query=[1,0], k=2
Output 0
a 1–1 vote tie → the smaller label wins
EXAMPLE 4
Input points=[[1,1],[2,2],[3,1],[6,5],[7,7],[1,3]], labels=[0,0,1,1,1,1], query=[2,1], k=4
Output 0
edge case: three points tie at distance 1, index order keeps all three plus point 5, and the 2–2 vote goes to the smaller label even though label 1 owns most of the data
CONSTRAINTS
  • Euclidean distance: √(Σ (pᵢ − qᵢ)²) across the feature dimensions.
  • Break distance ties by original index (earlier point in points is "nearer").
  • Break vote ties by returning the smaller integer label.
  • Pyodide has no numpy — use the math stdlib and plain lists only.
Hints 4 ideas
HINTS — 4 IDEAS
  1. For each training point compute √(Σ (pᵢ − qᵢ)²) to the query.
  2. Sort by (distance, original index) so equidistant points keep a stable order, then take the first k.
  3. Tally the labels of those k neighbors in a dict / Map.
  4. Return the label with the most votes; on a tie, the smaller label.
Approach, complexity & discussion — open after you solve

Start from brute force

The obvious approach, and the one the reference takes, computes the distance from the query to all n points, sorts all n, takes the first k and votes. It is correct: sorting (distance, index) pairs puts the k nearest first and applies the distance tie-break for free. It costs O(n·d + n log n) time for d-dimensional points and O(n) space for the distance list. The sort is the avoidable part, since only k positions matter, while the distance pass is not: without an index, every query still has to touch all n points, which is the real limit when queries are many and n is large.

The approach

Compute each distance once and keep only the k best seen so far. A max-heap of size k, keyed on (distance, index), holds the current k nearest; a new point replaces the worst entry only if it is closer, in O(log k). The invariant: after scanning i points, the heap holds the k smallest (d, i) pairs among them, so distance ties still go to the earlier index. Python’s heapq.nsmallest(k, dists) is documented as equivalent to sorted(dists)[:k].

At this size the reference takes the simpler route: it builds dists as (d, i) tuples, calls dists.sort(), tallies labels[i] for the first k in counts, and returns max(counts, key=lambda lab: (counts[lab], -lab)), which ranks by votes and then prefers the smaller label because -lab is larger for it. Comparing squared distances would skip the square root without changing the order.

0p00p11p21p31p41p5qsorted by (d, i); k = 4p0 d = 1.000 label 0p1 d = 1.000 label 0p2 d = 1.000 label 1p5 d = 2.236 label 1p3 d = 5.657 label 1p4 d = 7.810 label 1votes 0: 2, 1: 2, tie: smaller label 0
The walkthrough input. Three points tie at distance 1 and index order keeps all of them; the fourth slot goes to p5 at √5 ≈ 2.236, on the circle’s edge. Label 1 owns four of the six points, yet the 2–2 vote goes to label 0 by the smaller-label rule.

Walk through an example

With points = [[1,1],[2,2],[3,1],[6,5],[7,7],[1,3]], labels = [0,0,1,1,1,1], query = [2,1] and k = 4, three points tie at distance 1 and the vote ties 2 to 2, so both tie-breaks decide the answer, 0.

stepactionvaluescounts
1distance to each point1.0, 1.0, 1.0, 5.657, 7.810, 2.236{}
2sort by (d, i)points 0, 1, 2 (all 1.0), then 5 (2.236), 3, 4{}
3vote: point 0label 0{0: 1}
4vote: point 1label 0{0: 2}
5vote: point 2label 1{0: 2, 1: 1}
6vote: point 5label 1{0: 2, 1: 2}
7max by (count, -label)2 votes each; -0 beats -1returns 0

Complexity

Scoring is O(n·d) for n points in d dimensions. The reference’s full sort adds O(n log n) time and O(n) space for dists; a size-k heap makes selection O(n log k) with O(k) extra space. Voting is O(k). For many queries, a KD-tree (low d) or an approximate index such as HNSW (high d) avoids scanning all n points.

Edge cases to test

  • Equal distances keep input order: knn([[1,0],[-1,0],[0,5]], [1,0,0], [0,0], 1) returns 1, the label of point 0, because points 0 and 1 are both at distance 1 and the earlier index wins.
  • A vote tie goes to the smaller label: knn([[0,0],[2,0]], [1,0], [1,0], 2) returns 0, and a three-way tie, knn([[0,0],[1,0],[2,0]], [2,1,0], [1,0], 3), also returns 0.
  • k larger than the number of points: the Python reference slices past the end and votes over every point (knn([[0,0],[1,1]], [0,1], [0,0], 5) returns 0), but the TypeScript reference reads past the end of dists and throws a TypeError. Clamp k to len(points).
  • k = 0 leaves no votes: Python’s max raises ValueError on the empty counts, and TypeScript returns Infinity. Reject k < 1 up front.
  • Negative labels work, and the smaller one still wins a tie: knn([[0,0],[2,0]], [-1,3], [1,0], 2) returns -1.

Common mistakes

  • Not normalizing features — a single large-scale feature then dominates the distance and drowns out the rest.
  • Choosing k badly — k=1 is noisy and overfits, a huge k oversmooths across classes.
  • Brute-forcing at scale instead of using an approximate-nearest-neighbor index.
  • Breaking vote ties with max(counts, key=counts.get). Python’s max returns the first maximal key in insertion order, which is the label of the nearer point: on knn([[0,0],[2,0]], [1,0], [1,0], 2) it returns 1 instead of 0.

Follow-ups an interviewer asks next

What changes for regression instead of classification?
Replace the vote with the average of the k neighbors’ target values. A common refinement weights each neighbor by 1/d so closer points count more. That needs a guard for d = 0, where the query sits exactly on a training point, and the sensible answer is that point’s own value.
The dataset holds 10 million embedding vectors. How do you answer queries fast?
Exact search has to touch every vector, so use an approximate nearest-neighbor index, such as an HNSW graph or IVF clustering with product quantization. These trade a little recall for sub-linear query time, and recall is measured against brute force on a sample of queries. If the embeddings were trained for cosine similarity, normalize them and use inner product.
Should every neighbor get an equal vote?
Not necessarily. Distance-weighted voting gives each neighbor a weight such as 1/d, so one very close point can outvote two distant ones, and the result becomes less sensitive to the exact choice of k. Weighted votes rarely tie exactly, so the smaller-label rule then matters less.
How do you choose k?
By cross-validation: try several values and keep the one with the best held-out accuracy. A small k follows noise in the training labels; a large k blurs class boundaries and favors the majority class. With two classes an odd k makes vote ties impossible, though distance ties can still occur.

Where this shows up

k-NN is the conceptual core of vector search and RAG retrieval: “find the nearest embeddings to this query” is exactly k-NN, just run through an approximate index (HNSW) so it stays fast over millions of vectors. It also underlies recommendation and anomaly detection.

As a classifier it earns its place as a baseline. It has no training step, so it is the first thing to try on a new labeled dataset: if a 5-NN on standardized features already scores well, a heavier model has to beat that number to justify itself. It also explains its own predictions, because the answer comes with the k labeled examples that produced it, which a reviewer can inspect. Its weaknesses are predictable. Prediction cost grows with the training set, memory holds every point, and in high dimensions distances tend to concentrate for unstructured data, so the nearest and farthest points end up at similar distances; the features need real structure, which trained embeddings aim to provide. For anomaly detection the same machinery is turned around: the distance to the k-th nearest neighbor is the score, and a point far from all of its neighbors is flagged.

Check yourself

Same points and labels as the walkthrough, query [2, 1]. What does knn return for k = 3, 4 and 5?

0, 0, 1. With k = 3 the votes are p0, p1, p2: two for 0, one for 1. At k = 4 adding p5 makes it 2–2 and the smaller label wins. At k = 5 p3 joins and label 1 leads 3–2, which shows how sensitive a small vote is to k.

Same data, query [6, 6], k = 3. Which points vote, and what is the answer?

p3 at distance 1.0, p4 at √2 ≈ 1.414 and p1 at √32 ≈ 5.657, labels 1, 1 and 0, so it returns 1. The third neighbor is far away but still votes, since plain k-NN has no distance cutoff.

knn([[1, 1.0], [3, 1.2]], [0, 1], [2.9, 1.0], 1) returns 1. What happens if the second feature is recorded in units 1,000 times smaller, giving [[1, 1000], [3, 1200]] and query [2.9, 1000]?

It returns 0. The gap of 200 in the rescaled feature swamps the gap of 1.9 in the first, so p0 becomes the nearest even though nothing about the data changed. Standardize each feature, for example to zero mean and unit variance, before measuring distance.

For n = 1,000,000 points and k = 10, roughly how many comparisons does selection cost with the full sort versus a size-k heap?

A sort is about n log₂ n ≈ 2 × 107 comparisons, while the heap is about n log₂ k ≈ 3.3 × 106. Both are dwarfed by the distance pass when vectors have hundreds of dimensions, which is why large systems reach for an index rather than a cleverer selection.

Reference solution

Reference solution — Python
import math

def knn(points, labels, query, k):
    # distance to every training point, tagged with its index
    dists = []
    for i, p in enumerate(points):
        d = math.sqrt(sum((a - b) ** 2 for a, b in zip(p, query)))
        dists.append((d, i))
    dists.sort()  # by distance, then index — stable, deterministic
    # vote among the k nearest
    counts = {}
    for _, i in dists[:k]:
        lab = labels[i]
        counts[lab] = counts.get(lab, 0) + 1
    # most votes wins; smaller label breaks a tie
    return max(counts, key=lambda lab: (counts[lab], -lab))


print(knn([[0, 0], [10, 10]], [0, 1], [1, 1], 1))                    # -> 0
print(knn([[0, 0], [0, 1], [1, 0]], [0, 0, 1], [0, 0.4], 3))         # -> 0
Reference solution — TypeScript
function knn(points: number[][], labels: number[], query: number[], k: number): number {
  // distance to every training point, tagged with its index
  const dists = points.map((p, i) => {
    let s = 0;
    for (let j = 0; j < query.length; j++) s += (p[j] - query[j]) ** 2;
    return { d: Math.sqrt(s), i };
  });
  dists.sort((a, b) => a.d - b.d || a.i - b.i); // distance, then index
  // vote among the k nearest
  const counts = new Map<number, number>();
  for (let t = 0; t < k; t++) {
    const lab = labels[dists[t].i];
    counts.set(lab, (counts.get(lab) ?? 0) + 1);
  }
  // most votes wins; smaller label breaks a tie
  let best = Infinity;
  let bestCount = -1;
  for (const [lab, c] of counts) {
    if (c > bestCount || (c === bestCount && lab < best)) {
      best = lab;
      bestCount = c;
    }
  }
  return best;
}

console.log(knn([[0, 0], [10, 10]], [0, 1], [1, 1], 1));             // -> 0
console.log(knn([[0, 0], [0, 1], [1, 0]], [0, 0, 1], [0, 0.4], 3)); // -> 0

Questions about K-Nearest Neighbors

Does k-nearest neighbors need training?

No. k-NN is a lazy learner: fitting the model means storing the labeled points, and all the work happens at query time, when the distance from the query to every stored point is computed and the k nearest vote. That makes adding data instant, since there are no weights to update, but every prediction costs O(n times d) for n points in d dimensions unless you build an index. The real design decisions are the distance metric, the value of k, how the features are scaled, and how ties are broken.

Why do you need to normalize features for k-NN?

Euclidean distance adds up squared differences across features, so a feature measured in large units swamps the others. If one feature is income in dollars and another is age in years, a difference of 1,000 dollars outweighs a difference of 30 years, and the neighbors are chosen almost entirely by income. Standardizing each feature to zero mean and unit variance, or scaling it to a fixed range, makes each one count by its spread rather than its units. Fit the scaling on the training data and apply the same transform to every query.

How is k-NN related to vector search in RAG?

It is the same operation. A RAG retriever embeds the question, measures its similarity to every stored chunk embedding, and returns the k most similar chunks, which is k-nearest-neighbor search without the vote. At scale nobody scans every vector, so vector databases use approximate indexes such as HNSW that examine a small fraction of the vectors and still return most of the true nearest neighbors. Deterministic tie-breaking, as in this challenge, matters there too, because retrieval that changes between identical runs is hard to debug.

Why break distance ties by index and vote ties by the smaller label?

Both rules make the answer deterministic. When several points sit at exactly the same distance and only some fit inside k, something must decide which ones count, and the earlier index is the simplest stable rule: the reference gets it for free by sorting (distance, index) tuples. When labels tie on votes, max with the key (count, minus label) prefers the smaller label. Without these rules the answer could depend on the sort algorithm or on the order a dictionary was filled, and the hidden tests could not check it.

▶  Watch it explained
Finished this one? 0 / 76 Challenges done
NextBPE Merge Step Next on the “Model internals” ladder · rung 5 of 6

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Challenges