Euclidean distance matrixEasynumpylinear-algebradistancesvectorization
Euclidean distance matrix
Background
A distance matrix holds the pairwise distances between two sets of points — the core operation behind k-NN, k-means assignment, kernel methods, and clustering. Computing it efficiently uses the identity , which turns explicit per-pair subtraction into a single matrix product.
Problem statement
Implement pairwise_euclidean(A, B) returning the matrix of Euclidean distances between every row of A and every row of B:
Input
A—np.ndarrayof shape(n, d).B—np.ndarrayof shape(m, d).
Output
Returns an np.ndarray of shape (n, m) where D[i, j] is the distance from A[i] to B[j].
Examples
Example 1
Input: A = [[0, 0], [3, 4]], B = [[0, 0], [3, 0]]
Output: [[0, 3], [5, 4]]
Explanation: , , , and .
Constraints
- Vectorise via the identity — no Python loops over points.
- Clamp tiny negative squared distances to 0 before the square root.
- Output shape is
(n, m); tests compare withatol=1e-6.
Notes
- Squared distances can come out slightly negative from rounding;
np.maximum(sq, 0)beforesqrtavoids NaNs, notably on the zero diagonal whenAisB. - This is the kernel of k-NN and k-means: both reduce to "find the nearest row of
Bfor each row ofA".
Python
Loading...
This problem ships 4 hidden tests. They run in your browser via Pyodide — no backend, no submission queue. Press ▶ Run tests to execute.
- •Reference example
- •Matches brute-force pairwise distances
- •Self-distance matrix has a zero diagonal and is symmetric
- •Output shape is (n, m)