BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Optimization challenges1 of 14 in topic

872. Vectorise pairwise Euclidean distances

MediumOptimization challenges

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.

Functiondef 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

  • Y has 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).
Topics
Optimization challenges
Similar questions
  • Group-by mean without a Python loopMedium
  • Fast 2D valid convolutionMedium
  • Top-k indices for every rowMedium
  • IoU matrix for two sets of boxesMedium
All Optimization challenges problems
Report
872 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
7
8
9
10
11
import numpy as np
​
def pairwise_l2(X, Y):
X = np.asarray(X, dtype=float)
Y = np.asarray(Y, dtype=float)
D = np.zeros((X.shape[0], Y.shape[0]))
for i in range(X.shape[0]):
for j in range(Y.shape[0]):
D[i, j] = np.sqrt(np.sum((X[i] - Y[j]) ** 2))
return D
​

Run checks these cases in your browser, no sign-in needed. Submit checks all 4 tests.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS