Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path →
K-Nearest Neighbors
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.
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.
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).
Examples and constraints 4 examples
points=[[0,0],[10,10]], labels=[0,1], query=[1,1], k=10points=[[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=30points=[[0,0],[2,0]], labels=[1,0], query=[1,0], k=20points=[[1,1],[2,2],[3,1],[6,5],[7,7],[1,3]], labels=[0,0,1,1,1,1], query=[2,1], k=40- Euclidean distance:
√(Σ (pᵢ − qᵢ)²)across the feature dimensions. - Break distance ties by original index (earlier point in
pointsis "nearer"). - Break vote ties by returning the smaller integer label.
- Pyodide has no numpy — use the
mathstdlib and plain lists only.
Hints 4 ideas
- For each training point compute √(Σ (pᵢ − qᵢ)²) to the query.
- Sort by (distance, original index) so equidistant points keep a stable order, then take the first k.
- Tally the labels of those k neighbors in a dict / Map.
- 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.
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.
| step | action | values | counts |
|---|---|---|---|
| 1 | distance to each point | 1.0, 1.0, 1.0, 5.657, 7.810, 2.236 | {} |
| 2 | sort by (d, i) | points 0, 1, 2 (all 1.0), then 5 (2.236), 3, 4 | {} |
| 3 | vote: point 0 | label 0 | {0: 1} |
| 4 | vote: point 1 | label 0 | {0: 2} |
| 5 | vote: point 2 | label 1 | {0: 2, 1: 1} |
| 6 | vote: point 5 | label 1 | {0: 2, 1: 2} |
| 7 | max by (count, -label) | 2 votes each; -0 beats -1 | returns 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)returns1, 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)returns0, and a three-way tie,knn([[0,0],[1,0],[2,0]], [2,1,0], [1,0], 3), also returns0. klarger 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)returns0), but the TypeScript reference reads past the end ofdistsand throws aTypeError. Clampktolen(points).k = 0leaves no votes: Python’smaxraisesValueErroron the emptycounts, and TypeScript returnsInfinity. Rejectk < 1up 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
kbadly —k=1is noisy and overfits, a hugekoversmooths across classes. - Brute-forcing at scale instead of using an approximate-nearest-neighbor index.
- Breaking vote ties with
max(counts, key=counts.get). Python’smaxreturns the first maximal key in insertion order, which is the label of the nearer point: onknn([[0,0],[2,0]], [1,0], [1,0], 2)it returns1instead of0.
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/dso closer points count more. That needs a guard ford = 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)) # -> 0Reference 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)); // -> 0Questions 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.
Explore the topic
See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.
More Challenges
- SoftmaxThe function at the end of every classifier and language model: turn raw scores (logits) into a probability distribution. Implement the numerically stable version so big logits do not overflow. Solve it in Python or TypeScript.Read →
- Cosine SimilarityThe measure behind every embedding search and RAG system: how aligned are two vectors, ignoring their length? Dot product over the product of magnitudes — 1 identical, 0 orthogonal, -1 opposite. Solve it in Python or TypeScript.Read →
- Softmax with TemperatureThe dial that controls how "creative" a language model is: temperature scales the logits before the softmax — low sharpens toward greedy, high flattens toward uniform. Implement it, numerically stable. Solve it in Python or TypeScript, with hidden tests.Read →
- LRU CacheThe eviction policy behind every size-limited cache: when you run out of room, throw out whatever was used least recently. The trick is O(1) get and put — an ordered hash map (Python dict / JS Map) gives you exactly that. Solve it in Python or TypeScript.Read →
- Retry with Exponential BackoffTools time out and APIs rate-limit — a production agent retries without hammering. Exponential backoff waits longer after each failure (1s, 2s, 4s, 8s…) up to a cap. Compute the delay schedule: delay[i] = min(cap, base·2ⁱ). Solve it in Python or TypeScript.Read →
- Trim History to a Token BudgetEvery agent turn re-sends the whole conversation, so history must fit the context budget. Keep the most recent messages that fit and drop the oldest — the trimmer at the heart of context management. Solve it in Python or TypeScript.Read →