Skip to content
mlmentorship

Pairwise Squared Distances

Compute the squared distance from every point to every center without Python loops.

Published · 7 min read ·Role-specific ·Intermediate

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Pairwise Squared Distances

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. Float64 arrays points with shape (n, d) and centers with shape (k, d). Output. Return an (n, k) array whose entry [i, j] is the sum of squared coordinate differences. Do not take a square root: these are squared distances, not Euclidean distances themselves. Rules. Feature counts must match. Repeated points and empty axes are allowed; preserve both inputs. Differences, squares, and sums must remain representable in float64. Integer inputs are outside this numeric contract because they may overflow before reduction. Example. Points [[0, 0], [1, 2]] and centers [[0, 0], [1, 0]] return [[0, 1], [5, 4]]. The lower-right entry is 0 * 0 + 2 * 2 = 4.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Broadcast every point-center pair across a feature axis, square coordinate differences, then reduce that axis.

Problem trace

Sum squared coordinate differences; do not take a square root

Input and goalCompute the squared distance from every point to every center without Python loops.
Lay out points and centersUse points P0=(0,0), P1=(1,2) and centers C0=(1,0), C1=(2,2). The output must contain all four P-C pairs.
P0 (0,0)P0 (0,0)P1 (1,2)P1 (1,2)
columnsC0 (1,0), C1 (2,2)shapepair grid [n=2,k=2]
columns
C0 (1,0), C1 (2,2)
shape
pair grid [n=2,k=2]
C / row 0
P0 (0,0)

Recognize it
Use it when every item in one batch must pair with every item in another batch and the per-pair calculation is identical across a shared feature dimension.
Keep true
Cell [i,j,:] always belongs to point i and center j; broadcasting changes alignment, not values, and reducing only the final feature axis preserves the pair grid.
Reuse it
For all-pairs tensor operations, insert singleton axes where each operand should repeat, verify the broadcasted axis meaning, and reduce only the intended feature axes.
Use points P0=(0,0), P1=(1,2) and centers C0=(1,0), C1=(2,2). The output must contain all four P-C pairs. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Which axis disappears in the reduction? Why is the P0-C1 result eight rather than its square root?
Full interview answer 7 min read
Reading depth

Compute a table containing the squared Euclidean distance from every point to every center.

Problem

Input. Float64 arrays points with shape (n, d) and centers with shape (k, d).

Output. Return an (n, k) array whose entry [i, j] is the sum of squared coordinate differences. Do not take a square root: these are squared distances, not Euclidean distances themselves.

Rules. Feature counts must match. Repeated points and empty axes are allowed; preserve both inputs. Differences, squares, and sums must remain representable in float64. Integer inputs are outside this numeric contract because they may overflow before reduction.

Example. Points [[0, 0], [1, 2]] and centers [[0, 0], [1, 0]] return [[0, 1], [5, 4]]. The lower-right entry is 0 * 0 + 2 * 2 = 4.

Picture

For points (0,0), (1,2) and centers (1,0), (2,2), the output is [[1,8],[4,1]]. Inserted axes form (n,1,d) and (1,k,d) views. Their difference has shape (n,k,d); summing only the feature axis retains both ownership axes.

Problem trace

Separate point pair: squared displacement survives a common translation

Worked example: combine row norms with the cross-product, without a 3D difference tensorDistance measures the gap between points, not their individual positions relative to the origin. The norm-and-dot shortcut computes that same squared gap without building every pairwise difference vector. Moving both points together leaves the gap unchanged.The norm identity equals the actualsquared displacement(1,2)(3,2)Horizontal gap two; squareddisplacement four.Row norms: five and thirteen. Dotproduct: seven.Squared length of the gap: 4
Read it this way: Distance measures the gap between points, not their individual positions relative to the origin. The norm-and-dot shortcut computes that same squared gap without building every pairwise difference vector. Moving both points together leaves the gap unchanged. If both points move upward together, does their displacement change even though their individual norms change?
Reference drawing

Problem trace

Sum squared coordinate differences; do not take a square root

Worked example: combine row norms with the cross-product, without a 3D difference tensorDistance measures the gap between points, not their individual positions relative to the origin. The norm-and-dot shortcut computes that same squared gap without building every pairwise difference vector. Moving both points together leaves the gap unchanged.The norm identity equals the actualsquared displacement(1,2)(3,2)Horizontal gap two; squareddisplacement four.Row norms: five and thirteen. Dotproduct: seven.Squared length of the gap: 4
Execution trace
Input and goalCompute the squared distance from every point to every center without Python loops.
Lay out points and centersUse points P0=(0,0), P1=(1,2) and centers C0=(1,0), C1=(2,2). The output must contain all four P-C pairs.
P0 (0,0)P0 (0,0)P1 (1,2)P1 (1,2)
columnsC0 (1,0), C1 (2,2)shapepair grid [n=2,k=2]
columns
C0 (1,0), C1 (2,2)
shape
pair grid [n=2,k=2]
C / row 0
P0 (0,0)

Recognize it
Use it when every item in one batch must pair with every item in another batch and the per-pair calculation is identical across a shared feature dimension.
Keep true
Cell [i,j,:] always belongs to point i and center j; broadcasting changes alignment, not values, and reducing only the final feature axis preserves the pair grid.
Reuse it
For all-pairs tensor operations, insert singleton axes where each operand should repeat, verify the broadcasted axis meaning, and reduce only the intended feature axes.
Use points P0=(0,0), P1=(1,2) and centers C0=(1,0), C1=(2,2). The output must contain all four P-C pairs. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Which axis disappears in the reduction? Why is the P0-C1 result eight rather than its square root?
Read it this way: Distance measures the gap between points, not their individual positions relative to the origin. The norm-and-dot shortcut computes that same squared gap without building every pairwise difference vector. Moving both points together leaves the gap unchanged. If both points move upward together, does their displacement change even though their individual norms change?

Without singleton axes, subtraction may fail or compare corresponding rows instead of every point-center pair.

Code

import numpy as np

def pairwise_squared_distances(
   points: np.ndarray, centers: np.ndarray
) -> np.ndarray:
   differences = points[:, None, :] - centers[None, :, :]
   return np.sum(differences * differences, axis=-1)

Cost: time and temporary space.

The retained output additionally occupies space, including when the feature axis is empty.

Change the Requirement

Bound Pairwise Temporary Storage

New task: Emit point-row blocks rather than retaining every pairwise difference.

Picture and change: Keep center ownership fixed; restrict the active point axis to block_size.

Code: The reference still computes each complete block.

def squared_distance_blocks(points, centers, block_size: int):
   if block_size <= 0:
      raise ValueError("block_size must be positive")
   for start in range(0, len(points), block_size):
      yield start, pairwise_squared_distances(points[start:start + block_size], centers)

Check: Two point rows with block size one yield offsets 0,1 and rows [1,8], [4,1].

Use when: The consumer processes blocks; retaining them all still costs output storage.

Avoid the Three-Axis Difference

New task: Compute distances through norms and matrix multiplication.

Picture and change: Expand .

Code: Retain float64 shapes; require representable norm and product intermediates.

def squared_distances_gram(points, centers):
   point_norms = np.einsum("nd,nd->n", points, points)[:, None]
   center_norms = np.einsum("kd,kd->k", centers, centers)[None, :]
   result = point_norms + center_norms - 2 * (points @ centers.T)
   return np.maximum(result, 0.0)

Check: The small example still gives [[1,8],[4,1]].

Use when: Explicit array storage must scale as , excluding backend workspace. Cancellation can destroy small distances; clipping negatives does not restore lost accuracy.

Reconstruct

Why can the Gram expression return zero for distinct points?

Reasoned answer

In float64, point [[100000001.0]] and center [[100000000.0]] have direct squared distance 1. The Gram form subtracts nearly equal values around and returns 0 for this example. Subtracting nearby coordinates before squaring avoids that particular cancellation, but neither formulation prevents every overflow or rounding problem. Check representative magnitudes rather than treating algebraic equivalence as identical floating-point behavior.

The blocked version needs pairwise temporary storage and corresponding block-output storage. It does not reduce total arithmetic or automatically make the consumer streaming.