872. Vectorise pairwise Euclidean distances
Why it matters Distance matrices power k-NN, clustering, retrieval and kernel methods. Turning a double loop into broadcasting is the most common NumPy interview task.
pairwise_l2(X, Y) returns the Euclidean distance between every row of X and every row of Y: D[i, j] = sqrt(sum((X[i] - Y[j]) ** 2)).
Inputs: X is a list or ndarray of shape (n, d), Y of shape (m, d). Use np.asarray(..., dtype=float).
Return an ndarray of floats with shape (n, m). No rounding.
The starter is a correct but slow Python loop. Make it fast. The small tests check correctness. The last test runs your function on a large input and reports "fast enough" only if the call takes at most 40 times as long as a fixed 200,000-step pure Python loop on the same device. The test times both with time.perf_counter (input generation included), so the limit scales with your device and browser, and a call that is just over the limit is measured once more. Vectorised NumPy finishes far below the limit; the starter loop takes several times longer.
def pairwise_l2(X, Y)Example 1
Input: pairwise_l2([[0.0, 0.0], [3.0, 4.0]], [[0.0, 0.0], [6.0, 8.0], [3.0, 0.0]])
Output: [[0.0, 10.0, 3.0], [5.0, 5.0, 4.0]]
Example 2
Input: X = [[1.0, 2.0, 3.0]], Y = [[1.0, 2.0, 3.0]]
Output: [[0.0]]
Example 3
Input: X = [[1.0], [2.0], [5.0]], Y = [[0.0], [10.0]]
Output: [[1.0, 9.0], [2.0, 8.0], [5.0, 5.0]]
Constraints
Yhas shape(m, d)- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
Hint 1
Add axes with None so X and Y broadcast against each other.
Hint 2
Square, sum over the last axis, then sqrt.
Hint 3
The expansion trick with X @ Y.T is faster still but needs np.maximum(..., 0) before sqrt.
Common mistakes
- Summing over the wrong axis.
- Forgetting the sqrt.
- Using the matmul expansion without clamping negatives.
Understand the idea
Python loops pay interpreter overhead for every pair, so 450 x 450 = 202,500 tiny NumPy calls take seconds. Broadcasting X[:, None, :] - Y[None, :, :] builds all differences as one (n, m, d) array in C. For very large inputs you can use ||x||^2 - 2 x.y + ||y||^2 with one matrix multiply, but watch for small negative values from rounding before the sqrt.
Shapes and data flow
X: (n, d) -> (n, 1, d). Y: (m, d) -> (1, m, d). diff: (n, m, d). Output: (n, m).