Pairwise Distances
You are implementing the core distance computation for a K-Nearest Neighbors algorithm. Given N data points in D-dimensional space, you need to compute the Euclidean (L2) distance between every pair of points.
Given a 2D matrix where each row is a point in D-dimensional space, return a symmetric distance matrix D where:
D[i][j] = sqrt(sum((points[i][k] - points[j][k])^2 for k in range(dims)))
The diagonal must be exactly 0.0. Round each value to 6 decimal places.
Key insight: Use the identity ||a-b||² = ||a||² + ||b||² - 2·a·b to express the entire computation as a matrix multiplication — avoiding O(N²·D) nested loops.
Example 1
[[0, 0], [3, 4]][[0.0, 5.0], [5.0, 0.0]]Classic 3-4-5 right triangle. Distance = sqrt(3²+4²) = 5.0. Matrix is symmetric, diagonal is 0.0.
Example 2
[[1, 0], [0, 1], [-1, 0], [0, -1]][[0.0, 1.414214, 2.0, 1.414214], [1.414214, 0.0, 1.414214, 2.0], [2.0, 1.414214, 0.0, 1.414214], [1.414214, 2.0, 1.414214, 0.0]]Unit circle: adjacent points √2 apart, opposite points 2.0 apart.
Example 3
[[0, 0, 0], [3, 4, 0], [0, 5, 12]][[0.0, 5.0, 13.0], [5.0, 0.0, 12.409674], [13.0, 12.409674, 0.0]]Pythagorean triples: (3,4,0) is distance 5 from origin, (0,5,12) is distance 13.
- ›2 <= n_points <= 100
- ›1 <= n_dims <= 100
- ›-1000 <= points[i][j] <= 1000
Reference solution available after you attempt the question.
Ready to solve it?
Start a session on Mockbit #74. Write your code, run it against hidden tests, and get graded with specific critique on each axis.