KatInterview

Compute Correlation from Three Variance Values

Arrays & HashingAuto-graded · 21 test cases
MediumAuto-gradedArrays & Hashingstatisticsmathprobability

Last updated

Tests whether a candidate can apply the variance-of-a-sum identity to extract correlation, and correctly handle the case where one variance is missing.

Compute Correlation from Three Variance Values

You are given three quantities describing two random variables A and B with finite second moments:

  • var_sum: the variance of their sum, Var(A + B)
  • var_a: the variance of A, Var(A)
  • var_b: the variance of B, Var(B) — this may be absent (passed as None)

Implement a function that returns Corr(A, B) as a float, or None when the correlation cannot be determined.

Background

The variance of a sum expands as:

Var(A + B) = Var(A) + Var(B) + 2 · Cov(A, B)

Correlation is defined as:

Corr(A, B) = Cov(A, B) / sqrt(Var(A) · Var(B))

and is only meaningful when both variances are strictly positive.

Task

Given the three inputs above, return the correlation between A and B, subject to the following rules:

  1. If var_b is None, the correlation cannot be computed — return None.
  2. If either var_a or var_b is zero or negative, the correlation is undefined — return None.
  3. Otherwise, derive the covariance from the variance identity and return the correlation as a float.

Constraints

  • 0.0 <= var_sum (when provided as a real number)
  • var_a and var_b are real numbers; var_b may be None
  • These are population variances from a consistent probability model
  • You do not need to validate that the result falls within [-1, 1]; inputs are guaranteed to be consistent when all three values are present and positive

Examples

Example 1

Input: compute_correlation(13, 4, 9)

Output: 0

Example 2

Input: compute_correlation(5, 4, None)

Output: None

Example 3

Input: compute_correlation(2, 1, 1)

Output: 0

Hints

Hint 1

Start from the identity Var(A + B) = Var(A) + Var(B) + 2·Cov(A, B) and ask yourself: how many unknowns are there if var_b is missing?

Hint 2

When all three variances are available, rearrange the identity to isolate Cov(A, B), then remember that correlation divides by both standard deviations — not both variances.

Hint 3

Handle the two None-return cases (missing var_b, and non-positive variance) before doing any arithmetic.