Vectorized Pairwise Euclidean Distance Matrix in NumPy

Quick Overview

Implement a fully vectorized NumPy function that returns the matrix of Euclidean distances between every row of one point set and every row of another. It tests broadcasting across three axes, memory cost of large intermediates, and numerical stability of faster distance formulas.

Vectorized Pairwise Euclidean Distance Matrix in NumPy

Role: Data Scientist

Category: Data Manipulation (SQL/Python)

Difficulty: medium

Interview Round: Other

Implement `pairwise_distances(A, B)` where `A` has shape `(n, d)` and `B` has shape `(m, d)`. Return the `(n, m)` matrix `D` where `D[i, j]` is the Euclidean distance between `A[i]` and `B[j]`. For example: ```python A = np.array([[0.0, 0.0], [1.0, 0.0]]) B = np.array([[0.0, 0.0], [0.0, 1.0], [1.0, 1.0]]) pairwise_distances(A, B) # array([[0. , 1. , 1.41421356], # [1. , 1.41421356, 1. ]]) ``` ```hint Track the axes Write the shape of every intermediate array next to the line that creates it. Decide which axis indexes `A`, which indexes `B`, and which holds the coordinates, because only one of them should be summed away. ``` ```hint Check with known cases Test with `n`, `m` and `d` all different and assert the output shape is `(n, m)`. Swapped axes give the transpose, and a reduction over the wrong axis gives the wrong shape. Then check that distances from a point set to itself give a symmetric matrix with zeros on the diagonal. ``` ### Constraints & Assumptions - `A` and `B` share the same feature dimension `d`. - Form `A[:, None, :] - B[None, :, :]` (shape `(n, m, d)`), square, sum over the last axis, then `np.sqrt`. - Fully vectorized: no Python loops or comprehensions. ### What a Strong Answer Covers - How the reshaped operands line up so every `(i, j)` pair gets its own `d`-dimensional difference vector, and which axis the reduction runs over. - A loop-free implementation that returns shape `(n, m)` and reproduces the example. - The time and memory cost, including how large the `(n, m, d)` intermediate gets for realistic sizes. - A lower-memory alternative and the numerical problem it introduces for nearly identical points. - Input handling: mismatched `d`, integer dtypes and empty point sets. ### Follow-up Questions - The `(n, m, d)` intermediate blows up memory for large inputs. How would you avoid it? - Why can the norm-expansion approach produce tiny negative values before `sqrt`? - How would you find the `k` nearest rows of `B` for every row of `A` when even the `(n, m)` matrix does not fit in memory?

Overview: Implement a fully vectorized NumPy function that returns the matrix of Euclidean distances between every row of one point set and every row of another. It tests broadcasting across three axes, memory cost of large intermediates, and numerical stability of faster distance formulas.

Nov 25, 2026
mediumData ScientistOtherData Manipulation (SQL/Python)
0
0

Implement pairwise_distances(A, B) where A has shape (n, d) and B has shape (m, d). Return the (n, m) matrix D where D[i, j] is the Euclidean distance between A[i] and B[j].

For example:

A = np.array([[0.0, 0.0], [1.0, 0.0]])
B = np.array([[0.0, 0.0], [0.0, 1.0], [1.0, 1.0]])
pairwise_distances(A, B)
# array([[0.        , 1.        , 1.41421356],
#        [1.        , 1.41421356, 1.        ]])

Constraints & Assumptions

  • A and B share the same feature dimension d .
  • Form A[:, None, :] - B[None, :, :] (shape (n, m, d) ), square, sum over the last axis, then np.sqrt .
  • Fully vectorized: no Python loops or comprehensions.

What a Strong Answer Covers Guidance

  • How the reshaped operands line up so every (i, j) pair gets its own d -dimensional difference vector, and which axis the reduction runs over.
  • A loop-free implementation that returns shape (n, m) and reproduces the example.
  • The time and memory cost, including how large the (n, m, d) intermediate gets for realistic sizes.
  • A lower-memory alternative and the numerical problem it introduces for nearly identical points.
  • Input handling: mismatched d , integer dtypes and empty point sets.

Follow-up Questions Guidance

  • The (n, m, d) intermediate blows up memory for large inputs. How would you avoid it?
  • Why can the norm-expansion approach produce tiny negative values before sqrt ?
  • How would you find the k nearest rows of B for every row of A when even the (n, m) matrix does not fit in memory?