Euclidean Distance and K-Nearest Neighbor Indices
Easy · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
Represent every vector in d-dimensional space as a list of numeric coordinates (List[float]) of length d. Implement two functions:
- Vector Distance (
euclidean_distance(p, q)): Given two equal-length vectorspandq, return their straight-line Euclidean distance as afloat:sqrt((p[0] - q[0])^2 + (p[1] - q[1])^2 + ... + (p[d - 1] - q[d - 1])^2). - Nearest-Neighbor Retrieval (
k_nearest_neighbors(query_vector, k, dataset)— Judged): Given a target pointquery_vector, a positive integerk, and a list of candidate pointsdataset(each matchinglen(query_vector)), evaluate the Euclidean distance fromquery_vectorto every candidatedataset[i]. Return aList[int]holding the0-based indices of thekclosest entries indataset, ordered from smallest distance to largest distance. Whenever two entries indatasetsit at the exact same distance fromquery_vector, list the smallerdatasetindex first.
Examples
Example 1
Input:
query_vector = [2.0, 3.0]
k = 2
dataset = [[2.0, 6.0], [7.0, 15.0], [5.0, 3.0], [2.0, 1.0]]
Output: [3, 0]
Explanation: Distances from [2.0, 3.0] are 3.0 (index 0), 13.0 (index 1), 3.0 (index 2), and 2.0 (index 3). Index 3 is closest at 2.0; indices 0 and 2 tie at 3.0, so index 0 takes second place because 0 < 2.
Example 2
Input:
query_vector = [5.0, 5.0, 5.0]
k = 3
dataset = [
[9.0, 9.0, 9.0],
[4.0, 5.0, 5.0],
[7.0, 7.0, 7.0],
[1.0, 1.0, 1.0],
[5.0, 3.0, 5.0]
]
Output: [1, 4, 2]
Explanation: Distances to [5.0, 5.0, 5.0] are sqrt(48) ~= 6.9282 (index 0), 1.0 (index 1), sqrt(12) ~= 3.4641 (index 2), sqrt(48) ~= 6.9282 (index 3), and 2.0 (index 4). Ordering from closest to farthest picks indices 1, 4, and 2.
Example 3
Input:
query_vector = [-2.0, 4.0, -1.0]
k = 1
dataset = [[0.0, 4.0, -1.0], [-2.0, 4.0, -1.0], [-2.0, 1.0, -1.0]]
Output: [1]
Explanation: Candidate 1 coincides with query_vector at distance 0.0, beating index 0 (2.0) and index 2 (3.0).
Constraints
1 <= len(dataset) <= 10^4and1 <= k <= len(dataset).1 <= len(query_vector) <= 512, withlen(point) == len(query_vector)for everypointindataset.- Coordinates are finite integers or floating-point numbers (negative, zero, or positive).
- Leave
query_vectoranddatasetunmodified.
Step-by-step walkthrough
Understand the two parts and the tie-breaking rule
We are building two functions that work together:
euclidean_distance(p, q)— takes twod-dimensional vectors (lists of numbers with the same length) and returns their straight-line distance as afloat.k_nearest_neighbors(query_vector, k, dataset)— useseuclidean_distanceto find thekvectors indatasetclosest toquery_vectorand returns their indices (List[int]), ordered from closest to farthest.
Pay close attention to two rules in the specification: - Return indices into
dataset(such as[1, 4, 2]), not the coordinate vectors themselves. - If two dataset points are at the exact same distance fromquery_vector, the point with the smaller index indatasetmust come first.Part 1: compute Euclidean distance in d dimensions
In 2D, the straight-line distance between
p = [2, 3]andq = [7, 15]is the hypotenuse of a right triangle with horizontal leg7 - 2 = 5and vertical leg15 - 3 = 12:q = [7, 15] * | \ hypotenuse = sqrt(5^2 + 12^2) = sqrt(25 + 144) = 13.0 leg = 12 | \ |_____\ [7, 3] * p = [2, 3] leg = 5In
ddimensions, the exact same Pythagorean idea applies across alldcoordinates: subtract matching coordinatesp[i] - q[i], square each difference (so negative and positive differences both contribute positively), add them all up, and take one square root at the end:distance(p, q) = sqrt( (p[0] - q[0])^2 + (p[1] - q[1])^2 + ... + (p[d-1] - q[d-1])^2 )Even though the problem promises matching dimensions, checking
len(p) != len(q)up front is good engineering practice: a plainzip(p, q)in Python silently stops at the shorter list and would return a wrong number on buggy inputs instead of raising an error.def euclidean_distance(p: List[float], q: List[float]) -> float: """Compute the straight-line Euclidean distance between two d-dimensional vectors.""" # Guard against mismatched dimensions explicitly (zip() would silently drop extra coordinates). if len(p) != len(q): raise ValueError(f"Dimension mismatch: got {len(p)} and {len(q)}") # Accumulate sum of squared coordinate differences: sum((p[i] - q[i]) ** 2). squared_distance_sum = 0.0 for i in range(len(p)): coordinate_diff = p[i] - q[i] squared_distance_sum += coordinate_diff * coordinate_diff return math.sqrt(squared_distance_sum)Part 2: why we must inspect every point, and how to pick the k closest
Because
datasetis an arbitrary, unsorted list of points, the closest neighbor toquery_vectorcould sit at index0or at the very last index. That means any exact single-query algorithm must compute the distance to allnpoints, which takesO(n * d)coordinate operations inddimensions.Once we have all
ndistances, how should we select theksmallest in sorted order? - Sort allnpairs and slice the firstk:O(n log n)time, just a few crystal-clear lines of standard Python. - Maintain a size-kheap (heapq.nsmallest):O(n log k)time, helpful whennis in the millions andkis tiny (for examplek = 5), which we cover in the explanation.Since the prompt gives general in-memory inputs with
1 <= k <= len(dataset), sorting(distance, index)pairs is the cleanest and most direct solution.Key trick: let `(distance, index)` tuples handle tie-breaking
How do we sort by increasing distance and break ties by smaller index without writing custom comparator logic?
Python compares tuples in lexicographical order — slot by slot from left to right: 1. First it compares
pair_a[0]vspair_b[0](distance). Smaller distance wins. 2. Only when the two distances are equal (pair_a[0] == pair_b[0]), Python comparespair_a[1]vspair_b[1](index). Smaller index wins!Notice why we store
(distance, index)and not(distance, point, index): ifpointwere in the second slot, equal distances would compare point coordinates before reachingindex, violating the tie-breaking rule!def k_nearest_neighbors( query_vector: List[float], k: int, dataset: List[List[float]] ) -> List[int]: # distance_index_pairs: list of (distance, dataset_index) tuples, e.g. [(1.0, 1), (2.0, 4)] distance_index_pairs: List[Tuple[float, int]] = [] # Phase 1: Measure Euclidean distance from query_vector to every point in dataset. for index, point in enumerate(dataset): distance = euclidean_distance(query_vector, point) distance_index_pairs.append((distance, index)) # Phase 2: Tuple sort orders by smaller distance first, then smaller index on exact ties. distance_index_pairs.sort() # Phase 3: Extract the original dataset indices of the k closest points. nearest_indices: List[int] = [] for distance, index in distance_index_pairs[:k]: nearest_indices.append(index) return nearest_indicesTrace Example 2 and Example 1
Let's trace Example 2 first (
query_vector = [5.0, 5.0, 5.0],k = 3):index point coordinate diffs squared sum distance tuple 0 [9.0, 9.0, 9.0] (-4, -4, -4) 16+16+16=48 6.9282... (6.9282, 0) 1 [4.0, 5.0, 5.0] ( 1, 0, 0) 1+ 0+ 0= 1 1.0000 (1.0000, 1) 2 [7.0, 7.0, 7.0] (-2, -2, -2) 4+ 4+ 4=12 3.4641... (3.4641, 2) 3 [1.0, 1.0, 1.0] ( 4, 4, 4) 16+16+16=48 6.9282... (6.9282, 3) 4 [5.0, 3.0, 5.0] ( 0, 2, 0) 0+ 4+ 0= 4 2.0000 (2.0000, 4) After distance_index_pairs.sort(): 1st: (1.0000, 1) <- closest 2nd: (2.0000, 4) 3rd: (3.4641, 2) ------------------ (slice [:3] stops here) 4th: (6.9282, 0) 5th: (6.9282, 3) Returned indices: [1, 4, 2]Now check tie-breaking on Example 1 (
query_vector = [2.0, 3.0],k = 2,dataset = [[2.0, 6.0], [7.0, 15.0], [5.0, 3.0], [2.0, 1.0]]):Pairs before sort: [(3.0, 0), (13.0, 1), (3.0, 2), (2.0, 3)] Pairs after sort: [(2.0, 3), (3.0, 0), (3.0, 2), (13.0, 1)] ^^^^^^^^ ^^^^^^^^ tied at distance 3.0 -> index 0 comes before index 2! Returned indices: [3, 0]Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple import math def euclidean_distance(p: List[float], q: List[float]) -> float: """Compute the straight-line Euclidean distance between two d-dimensional vectors.""" # Guard against mismatched dimensions explicitly (zip() would silently drop extra coordinates). if len(p) != len(q): raise ValueError(f"Dimension mismatch: got {len(p)} and {len(q)}") # Accumulate sum of squared coordinate differences: sum((p[i] - q[i]) ** 2). squared_distance_sum = 0.0 for i in range(len(p)): coordinate_diff = p[i] - q[i] squared_distance_sum += coordinate_diff * coordinate_diff return math.sqrt(squared_distance_sum) def k_nearest_neighbors( query_vector: List[float], k: int, dataset: List[List[float]] ) -> List[int]: # distance_index_pairs: list of (distance, dataset_index) tuples, e.g. [(1.0, 1), (2.0, 4)] distance_index_pairs: List[Tuple[float, int]] = [] # Phase 1: Measure Euclidean distance from query_vector to every point in dataset. for index, point in enumerate(dataset): distance = euclidean_distance(query_vector, point) distance_index_pairs.append((distance, index)) # Phase 2: Tuple sort orders by smaller distance first, then smaller index on exact ties. distance_index_pairs.sort() # Phase 3: Extract the original dataset indices of the k closest points. nearest_indices: List[int] = [] for distance, index in distance_index_pairs[:k]: nearest_indices.append(index) return nearest_indices✅ Submit now — all tests should pass.
Intuition & how it works
Picture query_vector as your home on a map and dataset as a numbered list of coffee shops (0, 1, 2, ...). To find the k closest shops, you measure the straight-line "as-the-crow-flies" distance to every shop — called Euclidean distance (the square root of the sum of squared coordinate differences, which extends the familiar Pythagorean theorem a^2 + b^2 = c^2 to any number of dimensions). You write each measurement on an index card as (distance, shop_index), sort the stack of cards from smallest to largest, and read off the first k shop numbers. Because Python compares tuples in lexicographical order (comparing the first element first, and breaking ties with the second element), two shops at the exact same distance automatically stay ordered by their smaller original index!
Why do tempting shortcuts fail? Because dataset is unsorted, you cannot stop scanning early — the closest point in space might be sitting at the very last position of the list. And if you sort the dataset list itself or try to recover indices afterward with dataset.index(point), you both mutate the caller's input and get wrong answers whenever duplicate points exist (since list.index always returns the first copy's index, turning three identical points into [1, 1, 1] instead of [1, 2, 3]).
Here is a complete walkthrough on Example 1 (query_vector = [2.0, 3.0], k = 2, dataset = [[2.0, 6.0], [7.0, 15.0], [5.0, 3.0], [2.0, 1.0]]):
1. Compute (distance, index) for every point:
index 0: [2.0, 6.0] -> sqrt((2 - 2)^2 + (3 - 6)^2) = 3.0 -> ( 3.0, 0)
index 1: [7.0, 15.0] -> sqrt((2 - 7)^2 + (3 - 15)^2) = 13.0 -> (13.0, 1)
index 2: [5.0, 3.0] -> sqrt((2 - 5)^2 + (3 - 3)^2) = 3.0 -> ( 3.0, 2)
index 3: [2.0, 1.0] -> sqrt((2 - 2)^2 + (3 - 1)^2) = 2.0 -> ( 2.0, 3)
2. Sort tuples (ties at 3.0 break by 0 < 2):
[(2.0, 3), (3.0, 0), (3.0, 2), (13.0, 1)]
3. Take the first k = 2 indices:
[3, 0]
Complexity
Let n be the number of points in dataset and d be the dimensionality (number of coordinates per point).
- Time:
O(n * d + n log n). Computingeuclidean_distancefor one point loops across alldcoordinates inO(d)time, so scoring allnpoints takesO(n * d)time. Sorting then(distance, index)tuples with Timsort takesO(n log n)comparisons, and slicing out the firstkindices takesO(k)time (k <= n). - Space:
O(n).distance_index_pairsstores one(float, int)tuple for each of thendataset points, andnearest_indicesholdsk <= nintegers (the input lists are read-only and never copied).
Edge cases
k = 1andk = len(dataset):k = 1returns a single-element list with the closest point's index;k = len(dataset)returns a permutation of all0 .. n - 1ordered from closest to farthest.- Ties and duplicate points: Equal distances (including identical coordinate vectors in
dataset) always appear in ascending index order becauseindexis the second element of(distance, index). - Query point present in
dataset: Its Euclidean distance is0.0, which is the minimum possible distance, so its index appears first (as in Example 3). - 1D vectors, high-dimensional vectors, negative and fractional coordinates: Squaring
p[i] - q[i]makes every coordinate contribution non-negative regardless of sign or dimensiond >= 1. - Floating-point rounding on reordered decimals: With integers (whose squared sum fits below
2^53), mathematically equal distances produce identical floats. With arbitrary binary fractions, floating-point addition is not associative: from[0, 0, 0],[0.5, 0.2, 0.1]and[0.1, 0.2, 0.5]can differ by1bit in the last place (1e-16). If exact decimal tie-breaking is ever required, accumulate squared distances usingfractions.Fractionordecimal.Decimal. - Extreme coordinate magnitudes (
> 1e154): Squaringdiff * diffdirectly can overflow IEEE-754floatwhen|diff| > 1.34e154; Python's built-inmath.dist(p, q)(ormath.hypot) scales values internally to avoid overflow while computing the exact same formula.
Common mistakes
- Returning coordinate vectors or distances instead of indices: The function signature returns
List[int]containing dataset positions, notList[List[float]]. - Sorting points first and calling
dataset.index(point): Each.index()call scansdatasetinO(n)time (O(n * k)total) and always returns the first matching position, breaking whenever duplicate points exist. - Storing
(distance, point, index)or(distance, point): On distance ties, Python comparespointcoordinates beforeindex, violating the smaller-index tie-breaker. - Using
zip(p, q)without checking lengths:zip([2, 3], [2, 3, 100])silently ignores100instead of catching a buggy caller's dimension mismatch. - Using Manhattan distance by accident: Manhattan distance (the sum of absolute coordinate differences
sum(|p[i] - q[i]|), like walking along a city grid) ranks[0, 5](Manhattan5, Euclidean5.0) closer to[0, 0]than[3, 3](Manhattan6, Euclidean4.24), producing wrong neighbors. - Sorting
datasetin place: Callingdataset.sort(...)mutates the caller's list and destroys the original indices.
Alternative approaches
- Sort by squared distance directly: Because
sqrt(x)is strictly increasing forx >= 0, sorting(squared_distance_sum, index)produces the exact same neighbor order while skippingnsquare-root calls (and staying in exact integer arithmetic when coordinates are integers). We calleuclidean_distancedirectly here because the specification pairs the two functions explicitly. - Size-
kheap (O(n * d + n log k)time,O(k)memory): A heap (a tree stored in a flat array that keeps its extreme element at index0inO(log k)time per update) avoids sorting allnitems whenkis much smaller thann. In Python,heapq.nsmallest(k, ((euclidean_distance(query_vector, pt), idx) for idx, pt in enumerate(dataset)))streams the dataset inO(k)extra memory andO(n log k)comparisons. - Vectorized NumPy array operations: For numerical workloads, computing
squared = ((X - q) ** 2).sum(axis=1)in C and callingnp.argsort(squared, kind="stable")[:k]runs orders of magnitude faster than Python loops (kind="stable"preserves ascending index order on ties; note thatnp.argpartitionalone runs inO(n)average time but is not stable on elements tied at thek-th boundary without a tie-handling pass).
Follow-up questions
- How can you accelerate nearest-neighbor lookup when millions of queries target the same fixed dataset? Re-scanning all
npoints per query costsO(n * d)every time. In low dimensions (d <= 15or so), spatial trees like a k-d tree (a binary tree that recursively splits space along coordinate axes so branches farther away than the currentk-th best neighbor can be skipped) answer exact queries much faster than a linear scan. In high dimensions (such as 768-dimensional ML embeddings), tree pruning degrades toward scanning everything, so production systems use Approximate Nearest Neighbor (ANN) indexes like HNSW (navigable proximity graphs) or IVF-PQ (clustering plus vector compression), trading a tiny fraction of recall for 100x+ query speedups. - What extra steps turn
k_nearest_neighborsinto a supervised k-NN classifier or regressor on tabular features? For classification, look up the class labels of thekreturned indices and return the majority class (breaking label ties either by choosing an oddkfor binary tasks or weighting each neighbor's vote by1 / (distance + eps)so closer points count more). For regression, return the average (or inverse-distance-weighted average) of thekneighbors' target values. Before computing Euclidean distances on real-world tabular features, always apply feature standardization (rescaling each coordinate column to zero mean and unit variance), otherwise a feature measured in thousands (like salary in dollars) completely drowns out a feature measured in single digits (like years of experience). - How would you find the exact top-k neighbors when the dataset is too large to fit in memory or spans multiple machines? On a single machine, stream points one batch at a time and maintain a max-heap of size
kstoring(-distance, -index)(negated because Python'sheapqis a min-heap, so negating puts the worst of our current topkat the root ready to be replaced whenever a closer point appears), using onlyO(k)RAM. Across a distributed cluster, partition the dataset acrossMshards, have each shard return its local top-k(distance, global_index)pairs, and sort/merge thoseM * kcandidates on the coordinator node to pick the exact global topk.
Follow-up questions
- How can you accelerate nearest-neighbor lookup when millions of queries target the same fixed dataset?
- What extra steps turn `k_nearest_neighbors` into a supervised k-NN classifier or regressor on tabular features?
- How would you find the exact top-k neighbors when the dataset is too large to fit in memory or spans multiple machines?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array