Pairwise Squared Euclidean Distances in NumPy via the Gram Trick
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Implement `squared_dist_gram(A, B)` for `A` of shape `(n, d)` and `B` of shape `(m, d)`. Return the `(n, m)` matrix whose entry `[i, j]` is the **squared** Euclidean distance between `A[i]` and `B[j]`, using the identity
$$
\lVert a - b \rVert^2 = \lVert a \rVert^2 - 2\, a \cdot b + \lVert b \rVert^2
$$
The function must:
- Compute `(A**2).sum(axis=1)`, `(B**2).sum(axis=1)` and `A @ B.T`, and combine them with broadcasting (the norms shaped `(n, 1)` and `(1, m)`).
- Build no explicit `(n, m, d)` difference tensor and use no Python loops.
- Clip tiny negative values caused by floating-point error to `0`.
- Not take a square root.
Example:
```python
A = np.array([[0.0, 0.0], [1.0, 0.0]])
B = np.array([[0.0, 0.0], [0.0, 2.0]])
squared_dist_gram(A, B)
# array([[0., 4.],
# [1., 5.]])
```
```hint Shapes for broadcasting
Write down the shape of each of the three terms. The two norm vectors each need an extra axis before they line up with the `(n, m)` cross term.
```
```hint Near-identical rows
Think about the size of the three terms, and of their sum, when `A[i]` and `B[j]` are almost the same point.
```
### Constraints & Assumptions
- `A` has shape `(n, d)` and `B` has shape `(m, d)`, with the same `d`.
- The output has shape `(n, m)`.
### What a Strong Answer Covers
- The shape of every intermediate and how broadcasting combines the norm vectors with the cross term.
- Why the expansion avoids the `(n, m, d)` tensor, and what time and memory it costs instead.
- Where negative entries come from in floating point and why clipping is the right repair.
- Edge cases such as empty inputs, integer dtypes and mismatched feature dimensions.
### Follow-up Questions
- Why can entries go slightly negative, and why clip instead of taking `abs`?
- How would you handle `A is B` (a self-distance matrix) efficiently?
- When does this identity lose too much precision, and how would you reduce the error?
- How would you proceed when the `(n, m)` matrix is too large to hold in memory?
Overview: Compute every pairwise squared Euclidean distance between the rows of two NumPy matrices with vectorized code, without building a three-dimensional difference tensor or looping in Python. It tests broadcasting, matrix products, memory cost and floating-point cancellation.