The interview problem

Practice prompt

Compare two latency distributions whose observed values need not overlap. Explain Wasserstein distance, calculate an optimal transport plan for a small weighted example, and design a defensible distribution-drift check. Would a positive distance prove that the underlying population changed? Would checking every feature independently detect every kind of drift?

Original fundamentals practice, not a reported company interview. Examples are hypothetical. Official SciPy documentation and primary optimal-transport research consulted September 27, 2026.

1. Move probability mass under a meaningful cost

Let distribution P put mass aᵢ at xᵢ and Q put mass bⱼ at yⱼ. Each set of nonnegative masses sums to one. A coupling πᵢⱼ specifies how much mass moves from xᵢ to yⱼ. It must preserve both marginals:

πᵢⱼ ≥ 0
sum over j of πᵢⱼ = aᵢ
sum over i of πᵢⱼ = bⱼ
W₁(P,Q) = min over feasible π of sumᵢⱼ πᵢⱼ d(xᵢ,yⱼ)

For real-valued latency, use d(x,y) = |x−y|. Transport cost is mass times distance, minimized over feasible plans. It is not the cost of an arbitrary pairing. With a genuine ground metric and finite first moments, W₁ is a distance between probability distributions. An arbitrary asymmetric cost matrix need not produce a metric.

For p ≥ 1, Wₚ uses d(x,y)ᵖ inside the expectation and then takes the pth root, requiring finite pth moments for finite distance. The minimized squared-distance objective is W₂ squared, not W₂. The root restores the units of the ground distance.

2. Solve a weighted transport problem

Use P = 0.5δ₀ + 0.5δ₄ and Q = 0.25δ₁ + 0.75δ₃. Here δₓ means a point mass at x. Consider this plan:

FromToMassDistanceCost
010.2510.25
030.2530.75
430.5010.50

The row masses consume 0.5 at zero and 0.5 at four. The target receives 0.25 at one and 0.75 at three. Total cost is 1.5. Feasibility proves an upper bound; we still need optimality.

In one dimension, Wasserstein-1 equals the area between the two cumulative distribution functions:

W₁(P,Q) = integral over x of |Fₚ(x) − Fᵩ(x)| dx
IntervalCDF gapWidthArea
[0,1)0.5010.50
[1,3)0.2520.50
[3,4)0.5010.50

The gap is zero outside these intervals. The area is 1.5, proving our feasible plan is optimal. Endpoints have zero integration width and do not change the result.

An alternative sends 0.5 from zero to three, 0.25 from four to one and 0.25 from four to three. It is feasible, but costs 1.5 + 0.75 + 0.25 = 2.5. Taking that pairing as the distance would overestimate the optimum.

3. Do not replace transport with a mean comparison

In the worked example, E[P] = 2 and E[Q] = 2.5. Their mean difference is only 0.5, while W₁ is 1.5. For any coupling, |E[X]−E[Y]| ≤ E[|X−Y|], so the absolute mean difference is a lower bound on W₁, not a general formula for it.

For P = δ₀ and Q = δₕ, W₁ = |h|. When h is nonzero, both KL directions are infinite because each distribution puts all its mass where the other puts none. Transport still measures how far the locations are apart. This is useful when geometry matters, but it does not make transport universally preferable: categorical IDs assigned arbitrary numbers would invent a misleading geometry.

4. Preserve units and preprocessing

If inputs are milliseconds, W₁ is in milliseconds. Converting both distributions to seconds multiplies the distance by 0.001. Translating both by the same amount leaves it unchanged; multiplying both by c scales it by |c|. Report the metric and units with every threshold.

Do not independently center each comparison batch when location drift matters. Point masses at 10 and 20 have distance 10, but centering each by its own mean maps both to zero and erases the shift. Fit preprocessing on a fixed reference population, apply it consistently, and version it.

Normalizing counts to probability masses discards total volume. A hundred and a million requests can have identical normalized latency distributions and W₁ = 0. Monitor volume separately. If unequal total mass is central to the problem, define an appropriate mass-imbalance model explicitly rather than assuming ordinary probability transport captures it.

5. Identical marginals can hide joint drift

Let P place half its mass at (0,0) and half at (1,1). Let Q place half at (0,1) and half at (1,0). Both coordinate marginals are Bernoulli with probability 0.5. Therefore each one-dimensional coordinate comparison gives W₁ = 0.

Yet every source point is Euclidean distance one from every target point. All feasible plans move total mass one at cost one, so the joint Wasserstein-1 distance is exactly one. The dependence structure changed completely.

Sorting each coordinate independently destroys that dependence information. It cannot recover joint transport. For multidimensional features, specify the ground metric, feature scaling and computational method. A sum of marginal distances is a useful diagnostic with limits, not proof of equality of the joint distributions.

6. Compute the one-dimensional statistic efficiently

Sort the union of support values. Normalize valid nonnegative weights, accumulate both CDFs at each support location, and sum the absolute CDF difference times the width to the next location. Duplicate values can be aggregated. Sorting dominates at O((n+m) log(n+m)); no dense pairwise cost matrix is needed.

For equally sized, equally weighted one-dimensional samples, sorting each sample and averaging paired absolute differences gives W₁. Unequal sample sizes or weights require the weighted quantile or CDF calculation; pairing array positions arbitrarily is incorrect.

support = sorted union of observed values
for each adjacent pair (left, right):
    update both cumulative masses through left
    total += abs(cdf_P - cdf_Q) * (right - left)

Validate finite observations, nonnegative finite weights and a positive weight sum. For histogram data, use actual support coordinates and probability masses. Bucket IDs are not physical latency values. Density heights need bin-width conversion to masses, and representing a whole bin by its center introduces approximation error.

A dense 100,000 by 100,000 pairwise matrix contains 10¹⁰ entries. At eight bytes per entry it occupies 80 GB in decimal units before solver state. Higher-dimensional methods need their own computational and approximation analysis; the scalar sorting shortcut does not solve them.

7. Turn distance into a defensible drift check

Independent finite samples from the same population can have a positive empirical distance. The statistic alone is not a significance test or a proof of population change. Define reference and current populations, sample sizes, missingness handling and sampling units before interpreting it.

Calibrate expected variation using reference resampling or a permutation procedure when exchangeability is justified. For dependent time-series observations, arbitrary row permutation can invalidate the null model. Use a procedure appropriate to temporal dependence and seasonality, with block length and assumptions documented. For example, compare matching weekday and traffic cohorts rather than interpreting a changed mixture of peak and off-peak requests as an unexplained model shift. Preserve that population definition when calibrating thresholds.

Combine a prespecified statistical criterion with an operational effect-size threshold. Account for many monitored features or slices, and avoid selecting thresholds on the same incidents used to claim performance. Report sample size and uncertainty. A tiny statistically detectable change may be operationally irrelevant.

Input drift does not automatically imply model-quality degradation. Conversely, labels or the relationship between inputs and outcomes may change while the input distribution remains stable. Pair this statistic with outcome metrics, error analysis and service indicators when available.

8. Understand sensitivity and failure modes

For P = δ₀ and Q = 0.99δ₀ + 0.01δ₁₀₀₀, W₁ = 0.01 × 1,000 = 10. Although 99% of the mass stayed put, the distant tail matters. This is a consequence of mass times distance, not an automatic robustness guarantee. Compare tail quantiles and investigate whether extreme values are real incidents, unit errors or instrumentation faults.

  • Wrong geometry: numeric category IDs imply artificial proximity; choose a meaningful metric.
  • Moving normalization: per-batch scaling hides the shift being monitored; freeze reference preprocessing.
  • Histogram misuse: compare physical support and mass, not arrays of bucket counts as though they were observations.
  • Marginal blindness: unchanged coordinates can conceal dependence changes; evaluate joint structure where relevant.
  • Sampling noise: nonzero empirical distance is expected; calibrate a decision procedure.
  • Volume blindness: probability normalization removes request count information; monitor counts separately.
  • Task mismatch: a distribution change may not affect the model's decision; inspect downstream performance.

9. Follow-ups and self-review

Follow-ups: How would unequal sample weights change the calculation? What happens when only tail latency matters? Can two distributions have equal means and positive W₁? How would you compare mixed numerical and categorical features? What extra assumptions justify a drift p-value? Why is the squared W₂ objective not itself a metric in general?

  • Write both marginal constraints and check that the plan preserves mass.
  • Prove optimality for the worked example rather than showing only feasibility.
  • Distinguish W₁, W₂ and a generic transport cost.
  • State ground geometry, units and preprocessing.
  • Separate marginal from joint comparisons.
  • Separate empirical distance, statistical evidence and practical impact.
  • Explain histogram approximations and computational cost.
  • Account for tails, total volume and downstream model quality.

Sources and attribution

Retrieved September 27, 2026. No interview date applies. All numerical examples, counterexamples and monitoring scenarios are original practice material.

Continue your preparation

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