KatInterview

Spread of a Number List: Population Variance

Math & Bit ManipulationAuto-graded · 23 test cases
EasyAuto-gradedMath & Bit Manipulationvariancestatisticsfloating-point

Last updated

Implement population variance on a list of numbers without external libraries, handling empty and single-element inputs and choosing a numerically sound approach.

Measuring Spread

You are given a list of numbers (integers and/or floats). Write a function that returns how spread out the values are, measured as the population variance. Do not use external libraries such as NumPy or pandas.

Definition

Let n be the number of values and mu their arithmetic mean. The population variance is the average of the squared distances from the mean:

variance = (1 / n) * sum((x - mu)^2 for each x in the list)

Divide by n, not by n - 1.

Rules

  • Empty list: the variance is undefined, so raise a ValueError.
  • One element: return 0.0, since the single value equals its own mean.
  • Mixed numeric types: ints and floats may appear together. The result is a float (or a value equal to one, such as 2.0 for 2).
  • Return the variance as a single number.

Constraints

  • 0 <= len(values) <= 10^5
  • Each element is a finite int or float.
  • The input is a list, so it may be traversed more than once.
  • Aim for O(n) time and O(1) extra space.
  • Prefer subtracting the mean before squaring, rather than computing E[x^2] - E[x]^2, to avoid loss of precision when values are large and close together.

Examples

Example 1

Input: population_variance([1, 2, 3, 4, 5])

Output: 2

Example 2

Input: population_variance([4, 4, 4])

Output: 0

Example 3

Input: population_variance([2])

Output: 0

Hints

Hint 1

Start by computing the mean: the sum of the values divided by how many there are.

Hint 2

The variance is the average of the squared differences between each value and that mean. Divide by n, not n - 1.

Hint 3

Check for an empty list first and raise ValueError. Use a generator expression inside sum so no extra list is built.