InterviewPrepKit

Home / Coding / Machine Learning Coding / Numerical & Data / Pairwise Euclidean Distances

Pairwise Euclidean Distances

medium 00:00
Solving tips
  • Expand the squared norm: ||a-b||^2 = ||a||^2 - 2 a.b + ||b||^2, so the cross term is a single matrix product X @ Y.T.
  • Broadcast the two per-row squared-norm vectors into the (n,m) grid instead of looping over pairs.
  • Floating-point error can make a squared distance slightly negative; clip to 0 before sqrt or you get nan.

Compute the full matrix of Euclidean distances between two sets of points. Given X of shape (n, d) and Y of shape (m, d), produce the (n, m) matrix D where D[i, j] is the Euclidean distance between X[i] and Y[j]. This is the core of k-nearest-neighbors, k-means assignment, and RBF kernels, and interviewers use it to check whether you can vectorize a nested loop away.

Definition

The naive definition is a double loop over pairs:

D[i, j] = sqrt( sum_k (X[i, k] - Y[j, k])^2 )

The trick that removes both loops is the squared-norm expansion:

||a - b||^2 = ||a||^2 - 2 (a . b) + ||b||^2

Applied to all pairs at once, the cross term a . b becomes the single matrix product X @ Y.T, and the two norm terms broadcast across rows and columns.

Task

Complete pairwise_euclidean(X, Y) so it returns the (n, m) distance matrix, fully vectorized with NO Python loops. Use the expansion above: compute the per-row squared norms of X and Y, combine them with -2 * X @ Y.T, clip any tiny negative values (from floating-point error) up to 0, then take the square root. Do not call sklearn, scipy, or any built-in pairwise-distance helper.

Example

X = np.array([[0.0, 0.0],
              [1.0, 1.0]])
Y = np.array([[0.0, 0.0],
              [0.0, 3.0],
              [4.0, 0.0]])
pairwise_euclidean(X, Y)
# -> array([[0.        , 3.        , 4.        ],
#           [1.41421356, 2.        , 3.16227766]])

Row 0 measures the origin against each Y point; row 1 measures (1, 1) against the same three points, so D[1, 0] = sqrt(2) ≈ 1.4142.

Constraints

  • 1 <= n, m <= 10^4, 1 <= d <= 10^3; use vectorized NumPy, no Python loop over pairs.
  • Values fit in float64. The output is symmetric only when X and Y are the same array.
  • Clip small negative squared distances to 0 before sqrt to avoid nan.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug