The Spread

An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.

Domain
Python
Difficulty
easy
Seniority
L4
Asked in
Palantir

Problem

Given a list of numbers, return the sample variance (sum of squared deviations divided by n-1), rounded to 2 decimals. Return 0.0 when fewer than 2 numbers.

Data spread around a center. The range matters.

Example 1

Input:

nums = [6,7,3,9,10,15]

Output:

16.67

Example 2

Input:

nums = [1,1,1,1]

Output:

0

Worked solution and explanation

Why this problem exists in real interviews

This tests statistical computation from scratch, specifically the sample variance formula. It probes whether a candidate understands the difference between population variance (divide by n) and sample variance (divide by n-1), a distinction that matters in A/B testing.


Break down the requirements

Step 1: Handle the edge case of fewer than 2 elements

Sample variance requires at least 2 data points. Return 0.0 for lists with 0 or 1 elements.

Step 2: Compute the mean

Sum all values and divide by n.

Step 3: Compute the sum of squared deviations

For each value, compute (value - mean) ** 2 and accumulate.

Step 4: Divide by n-1 and round

Bessel's correction (n-1 denominator) gives an unbiased estimate of population variance.


The solution

Two-pass variance with Bessel correction
def sample_variance(nums: list) -> float:
    n = len(nums)
    if n < 2:
        return 0.0
    total = 0
    for val in nums:
        total += val
    mean = total / n
    sq_diff_sum = 0
    for val in nums:
        sq_diff_sum += (val - mean) ** 2
    result = round(sq_diff_sum / (n - 1), 2)
    return result

Common follow-up questions