FastPrepMean and Population Variance

Mean and Population Variance

Amazon logoAmazon● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

For this exercise, assume values is a nonempty one-dimensional array of finite numeric observations. Return its arithmetic mean and population variance as [mean, variance].

For n = values.length, the quantities are:

  • mean = sum(values[i]) / n.
  • variance = sum((values[i] - mean)^2) / n.

Use the divisor n, including when n = 1. A singleton or constant array therefore has variance 0. Return the variance, rather than its square root, and do not round the results to a fixed number of decimal places. Use double-precision arithmetic and avoid losing a small spread merely because all observations have a large offset.

Interview context and follow-up

The interview report describes a NumPy function computing mean and variance, followed by an MLE discussion. It does not specify the distribution or estimator convention.

For this exercise’s optional discussion, assume independent normal observations with an unknown mean and positive variance. Explain why a nonconstant sample’s maximum-likelihood variance uses n, how the unbiased sample estimator differs, and what changes when every observation is equal. This discussion does not change the returned statistics.

Function

meanAndVariance(values: double[]) → double[]

Examples

Example 1

values = [1.0,2.0,3.0,4.0]return = [2.5,1.25]

The mean is 2.5. Squared deviations sum to 5, so the population variance is 5 / 4 = 1.25.

Example 2

values = [-2.0,0.0,2.0]return = [0.0,2.6666666666666665]

The mean is 0. Squared deviations are 4, 0 and 4, so the population variance is 8 / 3.

Example 3

values = [999999.98,999999.99,1000000.0]return = [999999.99,6.666666679084301e-05]

The mean is approximately 999999.99. The deviations are approximately -0.01, 0 and 0.01, so the variance is approximately 0.0002 / 3. Large absolute values do not imply large variance.

Constraints

  • 1 <= values.length <= 1000.
  • Every observation is finite and in [-10^6, 10^6].
  • Use double precision. For each output coordinate, accepted error is at most 10^-6 * max(1, abs(expected)).

More Amazon problems

See Amazon hiring insights
public double[] meanAndVariance(double[] values) {
    // Return the mean followed by the population variance.
}
values[1.0,2.0,3.0,4.0]
expected[2.5,1.25]
Checking account…