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:

  1. Vector Distance (euclidean_distance(p, q)): Given two equal-length vectors p and q, return their straight-line Euclidean distance as a float: sqrt((p[0] - q[0])^2 + (p[1] - q[1])^2 + ... + (p[d - 1] - q[d - 1])^2).
  2. Nearest-Neighbor Retrieval (k_nearest_neighbors(query_vector, k, dataset) — Judged): Given a target point query_vector, a positive integer k, and a list of candidate points dataset (each matching len(query_vector)), evaluate the Euclidean distance from query_vector to every candidate dataset[i]. Return a List[int] holding the 0-based indices of the k closest entries in dataset, ordered from smallest distance to largest distance. Whenever two entries in dataset sit at the exact same distance from query_vector, list the smaller dataset index 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^4 and 1 <= k <= len(dataset).
  • 1 <= len(query_vector) <= 512, with len(point) == len(query_vector) for every point in dataset.
  • Coordinates are finite integers or floating-point numbers (negative, zero, or positive).
  • Leave query_vector and dataset unmodified.

Step-by-step walkthrough

  1. Understand the two parts and the tie-breaking rule

    We are building two functions that work together:

    1. euclidean_distance(p, q) — takes two d-dimensional vectors (lists of numbers with the same length) and returns their straight-line distance as a float.
    2. k_nearest_neighbors(query_vector, k, dataset) — uses euclidean_distance to find the k vectors in dataset closest to query_vector and 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 from query_vector, the point with the smaller index in dataset must come first.

  2. Part 1: compute Euclidean distance in d dimensions

    In 2D, the straight-line distance between p = [2, 3] and q = [7, 15] is the hypotenuse of a right triangle with horizontal leg 7 - 2 = 5 and vertical leg 15 - 3 = 12:

    q = [7, 15] *
                | \   hypotenuse = sqrt(5^2 + 12^2) = sqrt(25 + 144) = 13.0
      leg = 12  |   \
                |_____\
               [7, 3]  * p = [2, 3]
                  leg = 5
    

    In d dimensions, the exact same Pythagorean idea applies across all d coordinates: subtract matching coordinates p[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 plain zip(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)
    
  3. Part 2: why we must inspect every point, and how to pick the k closest

    Because dataset is an arbitrary, unsorted list of points, the closest neighbor to query_vector could sit at index 0 or at the very last index. That means any exact single-query algorithm must compute the distance to all n points, which takes O(n * d) coordinate operations in d dimensions.

    Once we have all n distances, how should we select the k smallest in sorted order? - Sort all n pairs and slice the first k: O(n log n) time, just a few crystal-clear lines of standard Python. - Maintain a size-k heap (heapq.nsmallest): O(n log k) time, helpful when n is in the millions and k is tiny (for example k = 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.

  4. 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] vs pair_b[0] (distance). Smaller distance wins. 2. Only when the two distances are equal (pair_a[0] == pair_b[0]), Python compares pair_a[1] vs pair_b[1] (index). Smaller index wins!

    Notice why we store (distance, index) and not (distance, point, index): if point were in the second slot, equal distances would compare point coordinates before reaching index, 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_indices
    
  5. Trace 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]
    
  6. 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). Computing euclidean_distance for one point loops across all d coordinates in O(d) time, so scoring all n points takes O(n * d) time. Sorting the n (distance, index) tuples with Timsort takes O(n log n) comparisons, and slicing out the first k indices takes O(k) time (k <= n).
  • Space: O(n). distance_index_pairs stores one (float, int) tuple for each of the n dataset points, and nearest_indices holds k <= n integers (the input lists are read-only and never copied).

Edge cases

  • k = 1 and k = len(dataset): k = 1 returns a single-element list with the closest point's index; k = len(dataset) returns a permutation of all 0 .. n - 1 ordered from closest to farthest.
  • Ties and duplicate points: Equal distances (including identical coordinate vectors in dataset) always appear in ascending index order because index is the second element of (distance, index).
  • Query point present in dataset: Its Euclidean distance is 0.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 dimension d >= 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 by 1 bit in the last place (1e-16). If exact decimal tie-breaking is ever required, accumulate squared distances using fractions.Fraction or decimal.Decimal.
  • Extreme coordinate magnitudes (> 1e154): Squaring diff * diff directly can overflow IEEE-754 float when |diff| > 1.34e154; Python's built-in math.dist(p, q) (or math.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, not List[List[float]].
  • Sorting points first and calling dataset.index(point): Each .index() call scans dataset in O(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 compares point coordinates before index, violating the smaller-index tie-breaker.
  • Using zip(p, q) without checking lengths: zip([2, 3], [2, 3, 100]) silently ignores 100 instead 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] (Manhattan 5, Euclidean 5.0) closer to [0, 0] than [3, 3] (Manhattan 6, Euclidean 4.24), producing wrong neighbors.
  • Sorting dataset in place: Calling dataset.sort(...) mutates the caller's list and destroys the original indices.

Alternative approaches

  • Sort by squared distance directly: Because sqrt(x) is strictly increasing for x >= 0, sorting (squared_distance_sum, index) produces the exact same neighbor order while skipping n square-root calls (and staying in exact integer arithmetic when coordinates are integers). We call euclidean_distance directly here because the specification pairs the two functions explicitly.
  • Size-k heap (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 index 0 in O(log k) time per update) avoids sorting all n items when k is much smaller than n. In Python, heapq.nsmallest(k, ((euclidean_distance(query_vector, pt), idx) for idx, pt in enumerate(dataset))) streams the dataset in O(k) extra memory and O(n log k) comparisons.
  • Vectorized NumPy array operations: For numerical workloads, computing squared = ((X - q) ** 2).sum(axis=1) in C and calling np.argsort(squared, kind="stable")[:k] runs orders of magnitude faster than Python loops (kind="stable" preserves ascending index order on ties; note that np.argpartition alone runs in O(n) average time but is not stable on elements tied at the k-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 n points per query costs O(n * d) every time. In low dimensions (d <= 15 or so), spatial trees like a k-d tree (a binary tree that recursively splits space along coordinate axes so branches farther away than the current k-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_neighbors into a supervised k-NN classifier or regressor on tabular features? For classification, look up the class labels of the k returned indices and return the majority class (breaking label ties either by choosing an odd k for binary tasks or weighting each neighbor's vote by 1 / (distance + eps) so closer points count more). For regression, return the average (or inverse-distance-weighted average) of the k neighbors' 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 k storing (-distance, -index) (negated because Python's heapq is a min-heap, so negating puts the worst of our current top k at the root ready to be replaced whenever a closer point appears), using only O(k) RAM. Across a distributed cluster, partition the dataset across M shards, have each shard return its local top-k (distance, global_index) pairs, and sort/merge those M * k candidates on the coordinator node to pick the exact global top k.

Follow-up questions

Similar questions

More Pitchbook interview questions

All 1 Pitchbook questions →