Back to Practice
#0038
Pairwise Distances To a Query Point
MediumNumPy20 min15 XP
Problem
Given a 2D array X and a 1D query point q, return a 1D array of Euclidean distances from each row of X to q.
Why This Matters
KNN, clustering, anomaly detection, and nearest-neighbor search all begin with distance calculations.
Function Signature
def distances_to_query(X, q):
Examples
Example 1
InputX = [[0, 0], [3, 4], [6, 8]], q = [0, 0]
Outputarray([0.0, 5.0, 10.0])
The points are 0, 5, and 10 units away from the origin.
Constraints
- X is a 2D numeric array.
- q has the same number of features as each row of X.
- Return distances in the same row order as X.
CodePython
Visible browser tests run here when available.
Testcases1 visible / 4 hidden categories
Distances from origin
InputX = [[0, 0], [3, 4], [6, 8]], q = [0, 0]
Expected[0.0, 5.0, 10.0]
This uses the 3-4-5 triangle twice.
Hidden Test Categories
Nonzero query pointThree-dimensional pointsSingle rowNegative coordinates