The interview problem

Practice prompt

Compress 100,000 fixed vectors from 10,000 dimensions for nearest-neighbor retrieval. Explain Gaussian random projection, choose a dimension using an explicit distortion and failure-probability target, and assess whether preserving distances guarantees preserving the nearest neighbor. Compare the theorem with an empirical 512-dimensional deployment candidate.

Original fundamentals practice, not a reported company interview. Examples are hypothetical. Primary projection references retrieved September 27, 2026.

1. Derive the scaling before using the transform

Let A be a k-by-d matrix with independent entries distributed as N(0,1/k), and map x to Ax. For a fixed nonzero difference vector v, each row's dot product with v is Gaussian with variance ||v||²/k. Consequently:

Z = ||Av||² / ||v||² ~ χ²(k) / k
E[Z] = 1
Var(Z) = 2/k

The factor 1/√k in entry standard deviation is essential. Using unscaled N(0,1) entries multiplies expected squared length by k. Expectation alone does not say that every pair in a large dataset has small distortion; some pairs may deviate substantially.

Use one persisted matrix and the same preprocessing for indexed items and queries. Independently projecting each request into a new random coordinate system makes its coordinates incompatible with the stored index.

2. Convert a fixed-pair tail into a finite-set guarantee

For 0 < ε < 1, a Gaussian squared-length concentration bound is:

Pr(|Z−1| ≥ ε) ≤ 2 exp(−k c)
c = ε²/4 − ε³/6

One way to obtain it uses the chi-square moment-generating function, E[exp(tχ²(k))] = (1−2t)^(−k/2), for t < 1/2. Chernoff optimization gives upper-tail exponent −k[ε−ln(1+ε)]/2 and lower-tail exponent −k[−ε−ln(1−ε)]/2. Bounding the logarithms yields the common, conservative expression above.

There are M = N(N−1)/2 unordered pairs among N fixed points. A union bound does not require these pair events to be independent. To make the probability of any pair violating the squared-distance bound at most δ, it is sufficient to choose:

2M exp(−k c) ≤ δ
k ≥ ceil(ln(N(N−1)/δ) / c)

(1−ε)||x−y||² ≤ ||Ax−Ay||² ≤ (1+ε)||x−y||²

The probability is over the random matrix for a finite dataset fixed independently of it. Zero-distance pairs remain zero and need no relative-error calculation. The bound is sufficient, not a claim that smaller dimensions cannot work.

3. Work out a dimension budget

For N = 100,000, ε = 0.2 and δ = 0.01:

c = 0.2²/4 − 0.2³/6 = 0.0086666667
k ≥ ceil(ln(100,000 × 99,999 / 0.01) / c)
  = 3,189

Thus 3,189 dimensions suffice under this particular Gaussian union-bound calculation for at least 99% probability of preserving all the fixed set's pairwise squared distances within 20%. The corresponding ordinary-distance factors are √0.8 and √1.2, not 0.8 and 1.2.

A 512-dimensional candidate can still be useful in practice, but this calculation does not certify it for the stated target. Measure its task performance and describe that as empirical evidence. If a sufficient bound exceeds the original dimension, it is not a useful compression certificate; the identity map preserves geometry exactly without compression.

4. Derive when nearest-neighbor order is preserved

Let the nearest and second-nearest squared distances from a query be d₁² and d₂², with 0 < d₁² < d₂². Under the pairwise bounds, a sufficient condition for preserving their order is:

(1+ε)d₁² < (1−ε)d₂²
d₂²/d₁² > (1+ε)/(1−ε)

At ε = 0.2, the squared-distance ratio must exceed 1.5, or the ordinary-distance ratio must exceed √1.5 ≈ 1.2247. This is sufficient, not necessary, and assumes the query-to-item pairs are covered by the guarantee.

Original squared distancesAllowed near upper boundAllowed far lower boundConclusion
1 and 1.11.20.88The distortion guarantee alone does not rule out reversal
1 and 21.21.6Order is preserved under the bounds

If d₁² = 0, the identical vector stays at zero distance; any competitor with positive distance remains positive under the bounds. Multiple identical vectors remain tied. The first row is an insufficiency argument, not a claim that arbitrary extreme distortions can simultaneously occur for every dataset. Small ranking margins require direct retrieval evaluation even when average distance distortion looks good.

5. Respect the finite-set scope

For k < d, A has a nontrivial nullspace. Some nonzero vector v satisfies Av = 0, so no such linear map can preserve every distance throughout all of Rᵈ. A finite-set guarantee does not contradict this.

A fixed finite collection of future queries independent of the random matrix can be included in the analysis, with an adjusted pair count. Queries chosen adaptively after inspecting the transform need additional analysis. Measuring a thousand sampled pairs does not establish the maximum distortion over billions of pairs.

Random projection also does not provide encryption or a privacy guarantee. Lower dimensionality alone does not establish that sensitive attributes cannot be recovered or inferred.

6. Compare the right geometry and baseline

PCA selects directions using the fitted data and optimizes a reconstruction objective under its assumptions. Random projection uses a data-independent transform with probabilistic geometry preservation. Neither universally dominates: compare reconstruction, retrieval quality, fit cost and deployment stability for the actual use case.

For unit vectors, original squared Euclidean distance equals 2−2cosine similarity. Projected norms vary. Renormalizing projected vectors changes the geometry again, so do not apply the unnormalized squared-distance inequality unchanged without analysis. Evaluate the final metric used by the index.

Preserving a poor input metric does not make it useful. Freeze meaningful feature preprocessing, and avoid changing scale independently between index and query batches. Sparse projections can reduce transform storage and arithmetic, but use an appropriate distribution and scaling rather than deleting Gaussian entries arbitrarily.

7. Include transform memory and computation

For the empirical k = 512 candidate with float32 storage:

original vectors: 100,000 × 10,000 × 4 = 4 GB
projected vectors: 100,000 × 512 × 4 = 204.8 MB
projection matrix: 512 × 10,000 × 4 = 20.48 MB
vector-storage reduction: 10,000/512 ≈ 19.53×

These decimal sizes exclude index structures, replicas and metadata. A dense Gaussian transform may turn sparse input into dense output, so the dense-to-dense storage comparison is not universally representative.

Projecting all vectors requires about 100,000 × 512 × 10,000 = 512 billion multiply-accumulate pairs for a straightforward dense implementation. A query costs 5.12 million such pairs before search. Compression can reduce index costs while adding substantial transformation work.

A pseudoinverse can reconstruct a vector consistent with projected coordinates, but it cannot generally recover information lost in the nullspace. A successful projection-after-reconstruction check is not proof of recovering the original vector.

8. Validate geometry and the retrieval task

Measure squared-distance ratios on ordinary sampled pairs and on hard near-neighbor pairs. Report the distribution and maximum among the pairs actually examined, with duplicate points handled separately. Test several candidate dimensions and random seeds on validation data, then use an untouched query set for the final selected artifact.

Measure recall at the intended retrieval depth, downstream task quality, index memory, build time and latency. High average pairwise accuracy can hide the small ordering errors that matter to nearest-neighbor search. Avoid selecting the best seed on the final test set and presenting that result as independent validation.

Persist the transform matrix or an equivalently reproducible artifact, preprocessing version, dimensions and index compatibility identifier. A seed without the generator implementation and configuration may not reproduce the same matrix after an upgrade. Rebuild or migrate the index when changing the transform.

9. Failure analysis and self-review

Common failures include missing variance scaling, mixing projection matrices, confusing squared and ordinary distance bounds, using a finite-set result for adaptive inputs, overlooking small neighbor margins, and reporting dense storage savings for an originally sparse workload.

Follow-ups: How does δ change the dimension budget? What if the query is identical to an indexed vector? Does preserving distances preserve all classification decisions? Can PCA outperform a random map here? What evidence supports a smaller empirical dimension? How would you migrate an index without mixing coordinate systems?

  • Derive fixed-vector expectation and variance.
  • State the probability space, finite-set assumption and union bound.
  • Calculate a sufficient dimension without calling it necessary.
  • Distinguish squared-distance distortion from ranking preservation.
  • Account for query pairs and small neighbor margins.
  • Budget transform computation and representation memory.
  • Validate the deployed metric and persist compatible artifacts.

Sources and attribution

Retrieved September 27, 2026. No interview date applies. The explicit δ-dependent Gaussian calculation, nearest-neighbor examples and resource budget are worked here; they are not quoted library defaults or measured production results.

Continue your preparation

Choose a connected learning path or browse more ML fundamentals questions. Read our editorial method and attribution policy.