Identifiability and Derivation of Correlation from Variance Terms
Medium · Statistics & Math · Data Scientist · Technical Screen
Problem Statement
Let X and Y be two random variables with finite second moments governed by a common probability distribution. You are provided var_sum = Var(X + Y) and var_x = Var(X), along with an optional third argument var_y = Var(Y) (None when Var(Y) is omitted).
Implement derive_correlation(var_sum, var_x, var_y) to address both identifiability and exact calculation of the Pearson correlation Corr(X, Y):
- Identifiability check (
var_y is None): When onlyVar(X + Y)andVar(X)are supplied, the identityVar(X + Y) = Var(X) + Var(Y) + 2 * Cov(X, Y)leaves two unknown quantities (Var(Y)andCov(X, Y)) in a single equation, and the denominatorsqrt(Var(X)) * sqrt(Var(Y))is also unknown. After checking thatvar_sumandvar_xare finite and non-negative, returnNone. - Closed-form derivation (
var_yprovided): Whenvar_x > 0andvar_y > 0, isolate covariance asCov(X, Y) = (Var(X + Y) - Var(X) - Var(Y)) / 2and returnCov(X, Y) / (sqrt(Var(X)) * sqrt(Var(Y))). - Degenerate zero-variance handling (
var_x == 0orvar_y == 0): A zero-variance variable is constant and has zero covariance with every variable, requiringVar(X + Y) == Var(X) + Var(Y)(within floating-point relative tolerance1e-9). ReturnNonewhen consistent because correlation is undefined (0 / 0), or raise aValueErrorifVar(X + Y)disagrees. - Domain and feasibility checks: Raise a
ValueErrorif any supplied variance is non-finite (NaNorinf) or negative, or if the implied correlation falls outside[-1, 1]beyond benign IEEE-754 rounding (1e-9). Clamp slight boundary rounding overshoots back into[-1.0, 1.0].
Examples
Example 1
Input: var_sum = 52, var_x = 9, var_y = 25
Output: 0.6
Walk-through: Isolating covariance gives Cov(X, Y) = (52 - 9 - 25) / 2 = 9.0. Dividing by the product of standard deviations sqrt(9) * sqrt(25) = 3 * 5 = 15 yields 9.0 / 15 = 0.6.
Example 2
Input: var_sum = 18, var_x = 9, var_y = None
Output: None
Walk-through: With Var(Y) unknown (None), 18 - 9 = Var(Y) + 2 * Cov(X, Y) admits infinitely many valid correlations across [-1, 1], so Corr(X, Y) is unidentifiable and the function returns None.
Example 3
Input: var_sum = 49, var_x = 25, var_y = 64
Output: -0.5
Walk-through: Here Cov(X, Y) = (49 - 25 - 64) / 2 = -20.0, and dividing by sqrt(25) * sqrt(64) = 5 * 8 = 40 produces -20.0 / 40 = -0.5.
Constraints
- Numeric variance inputs can range from
0.0and tiny sub-unit magnitudes (1e-300) up to1e200, or invalid values (< 0,inf,nan). - Avoid overflowing or underflowing
var_x * var_ywhen computing the denominator at extreme scales. - Every returned numeric correlation must satisfy
-1.0 <= result <= 1.0.
Step-by-step walkthrough
Understand the goal and definitions
Before writing any equations, let's define the building blocks in plain English:
- Variance (
Var(X)) is the average squared distance of a random variableXfrom its meanE[X]. It measures how spread outXis, and it can never be negative. - Standard deviation (
sd_x = sqrt(Var(X))) puts that spread back into the original units ofX. - Covariance (
Cov(X, Y)) is the average product(X - E[X]) * (Y - E[Y]). It is positive whenXandYtend to rise together, negative when one rises as the other falls, and0when they have no linear relationship. - Pearson correlation (
Corr(X, Y)) divides the covariance by both standard deviations so the result is unit-free and always sits in[-1, 1]:
Corr(X, Y) = Cov(X, Y) / (sqrt(Var(X)) * sqrt(Var(Y)))Our function
derive_correlation(var_sum, var_x, var_y)receivesvar_sum = Var(X + Y),var_x = Var(X), andvar_y = Var(Y)(orNonewhenVar(Y)is not provided). The two parts of the interview question map directly to the two branches of the function:- Part 1 (
var_y is None): decide whetherCorr(X, Y)can be determined fromVar(X + Y)andVar(X)alone. - Part 2 (
var_yis given): computeCorr(X, Y)when the variances are valid and positive, returnNonewhen a zero variance leaves correlation undefined, and raiseValueErrorwhen the inputs are mathematically impossible.
- Variance (
Derive the variance-of-a-sum identity
Why does
Var(X + Y)tell us anything about howXandYmove together? Writedx = X - E[X]anddy = Y - E[Y]for the deviations from each mean. BecauseE[X + Y] = E[X] + E[Y], the deviation ofX + Yfrom its mean is simplydx + dy.Squaring
(dx + dy)with the ordinary algebra rule(a + b)^2 = a^2 + b^2 + 2aband taking expectations term by term gives the variance-of-a-sum identity:Var(X + Y) = E[((X + Y) - E[X + Y])^2] = E[(dx + dy)^2] = E[dx^2] + E[dy^2] + 2 * E[dx * dy] = Var(X) + Var(Y) + 2 * Cov(X, Y)Visually, the total spread of
X + Yhas three pieces:|<------------------ Var(X + Y) ------------------>| |---- Var(X) ----|---- Var(Y) ----|-- 2*Cov(X,Y) --|When
Cov(X, Y) > 0, the2 * Cov(X, Y)term stretchesVar(X + Y)aboveVar(X) + Var(Y). WhenCov(X, Y) < 0, the two variables partly cancel each other out and shrinkVar(X + Y)belowVar(X) + Var(Y).Part 1: Why correlation is not identifiable without Var(Y)
In statistics, a quantity is identifiable if the known information pins it down to a single possible value. Suppose we are given only
Var(X + Y)andVar(X), whileVar(Y)is missing (var_y is None). Look at the identity:Var(X + Y) - Var(X) = Var(Y) + 2 * Cov(X, Y) (known number) = (unknown #1) + 2 * (unknown #2)We have one equation with two unknowns (
Var(Y)andCov(X, Y)), so infinitely many pairs(Var(Y), Cov(X, Y))produce the exact sameVar(X + Y)andVar(X). Worse still, even if someone handed usCov(X, Y), the formulaCov(X, Y) / (sqrt(Var(X)) * sqrt(Var(Y)))still requiressqrt(Var(Y))in the denominator.A concrete counterexample proves that any correlation in
[-1, 1]can fit the same two numbers. FixVar(X) = 4andVar(X + Y) = 16:Choice of Y Var(Y) Cov(X, Y) Var(X) + Var(Y) + 2*Cov Corr(X, Y) -------------------------------------------------------------------------------- Y = X 4 4 4 + 4 + 8 = 16 +1.0 Y independent of X 12 0 4 + 12 + 0 = 16 0.0 Y = -3 * X 36 -12 4 + 36 - 24 = 16 -1.0All three choices have
Var(X) = 4andVar(X + Y) = 16, yet their correlations span-1.0,0.0, and+1.0. So after checking that the given variances are finite and non-negative, we returnNonewhenevervar_y is None:if not (math.isfinite(var_sum) and math.isfinite(var_x)): raise ValueError("variances must be finite numbers") if var_sum < 0 or var_x < 0: raise ValueError("a variance cannot be negative") if var_y is None: return NonePart 2: Solve for covariance and correlation when Var(Y) is given
Once
Var(Y)is also given,Cov(X, Y)is the only unknown left inVar(X + Y) = Var(X) + Var(Y) + 2 * Cov(X, Y). SubtractVar(X)andVar(Y)from both sides and divide by2:2 * Cov(X, Y) = Var(X + Y) - Var(X) - Var(Y) Cov(X, Y) = (Var(X + Y) - Var(X) - Var(Y)) / 2When
Var(X) > 0andVar(Y) > 0, dividingCov(X, Y)bysqrt(Var(X)) * sqrt(Var(Y))gives the correlation:Corr(X, Y) = (Var(X + Y) - Var(X) - Var(Y)) / (2 * sqrt(Var(X)) * sqrt(Var(Y)))In code, we compute
math.sqrt(var_x)andmath.sqrt(var_y)separately before multiplying them. If we wrotemath.sqrt(var_x * var_y)instead, large inputs likevar_x = var_y = 1e200would overflowvar_x * var_ytoinf(silently turning any correlation into0.0), and tiny inputs like1e-300would underflowvar_x * var_yto0.0(crashing withZeroDivisionError).covariance = (var_sum - var_x - var_y) / 2.0 std_x = math.sqrt(var_x) std_y = math.sqrt(var_y) correlation = covariance / (std_x * std_y)Handle zero variances and impossible inputs
Real-world numerical inputs need two safety checks so we never divide by zero or return an impossible correlation like
1.4:- Zero variance (
var_x == 0orvar_y == 0): A variable with zero variance is a constant, and a constant never varies with anything, soCov(X, Y)must be0. That meansVar(X + Y)must equalVar(X) + Var(Y)(allowing a tiny relative tolerance1e-9for float rounding). Ifcovarianceis non-zero, the three numbers contradict each other and we raiseValueError. If they are consistent, correlation is still0 / 0(undefined), so we returnNone. - The
[-1, 1]range check: By the Cauchy-Schwarz inequality (which guarantees|Cov(X, Y)| <= sd_x * sd_yfor every pair of random variables),Corr(X, Y)must lie between-1and+1. Equivalently,Var(X + Y)must sit between(sd_x - sd_y)^2and(sd_x + sd_y)^2. Ifabs(correlation) > 1.0 + TOLERANCE, no random variables(X, Y)could ever have those three variances, so we raiseValueError. Otherwise we clampcorrelationto[-1.0, 1.0]in case float rounding produced1.0000000000000002at a true boundary of1.0.
if var_x == 0 or var_y == 0: scale = var_sum + var_x + var_y if abs(covariance) > TOLERANCE * scale: raise ValueError("inconsistent variances: a constant variable has zero covariance") return None std_x = math.sqrt(var_x) std_y = math.sqrt(var_y) correlation = covariance / (std_x * std_y) if abs(correlation) > 1.0 + TOLERANCE: raise ValueError("inconsistent variances: |correlation| would exceed 1") return max(-1.0, min(1.0, correlation))- Zero variance (
Trace through the three examples
Let's trace the three examples from the problem statement:
Inputs (var_sum, var_x, var_y) covariance = (sum - x - y)/2 std_x * std_y Output ---------------------------------------------------------------------------------------- (52, 9, 25) (52 - 9 - 25) / 2 = 9.0 3 * 5 = 15 0.6 (18, 9, None) var_y is missing (Part 1) unknown None (49, 25, 64) (49 - 25 - 64) / 2 = -20.0 5 * 8 = 40 -0.5In Example 1,
Var(X + Y) = 52exceeds the uncorrelated sum9 + 25 = 34, yieldingCorr(X, Y) = +0.6. In Example 3,Var(X + Y) = 49sits well below25 + 64 = 89, yieldingCorr(X, Y) = -0.5.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple import math # Small relative/absolute slack so benign IEEE-754 float rounding at the # boundaries (-1.0, 0.0, +1.0) is not mistaken for impossible input. TOLERANCE = 1e-9 def derive_correlation(var_sum: float, var_x: float, var_y: Optional[float]) -> Optional[float]: # Phase 1: Validate that all provided variances are finite and non-negative. # Checking math.isfinite first catches NaN, which would otherwise slip past '< 0'. if not (math.isfinite(var_sum) and math.isfinite(var_x)): raise ValueError("variances must be finite numbers") if var_sum < 0 or var_x < 0: raise ValueError("a variance cannot be negative") # Part 1 (Identifiability): Without Var(Y), one equation Var(X + Y) = Var(X) + Var(Y) + 2*Cov(X, Y) # has two unknowns (Var(Y) and Cov(X, Y)), so Corr(X, Y) cannot be determined in general. if var_y is None: return None if not math.isfinite(var_y): raise ValueError("variances must be finite numbers") if var_y < 0: raise ValueError("a variance cannot be negative") # Phase 2: Rearrange Var(X + Y) = Var(X) + Var(Y) + 2 * Cov(X, Y) to isolate covariance. covariance = (var_sum - var_x - var_y) / 2.0 # Phase 3: Handle degenerate zero-variance variables before dividing by standard deviations. if var_x == 0 or var_y == 0: # A constant variable has zero covariance with everything, so Var(X + Y) must equal Var(X) + Var(Y). scale = var_sum + var_x + var_y if abs(covariance) > TOLERANCE * scale: raise ValueError("inconsistent variances: a constant variable has zero covariance") # Even when consistent, correlation divides by zero standard deviation and is undefined. return None # Phase 4: Normalize covariance by both standard deviations. # Take two separate square roots instead of sqrt(var_x * var_y) so extreme scales # like 1e200 or 1e-300 do not overflow to inf or underflow to 0.0. std_x = math.sqrt(var_x) std_y = math.sqrt(var_y) correlation = covariance / (std_x * std_y) # By Cauchy-Schwarz, any valid pair (X, Y) satisfies -1 <= Corr(X, Y) <= 1. if abs(correlation) > 1.0 + TOLERANCE: raise ValueError("inconsistent variances: |correlation| would exceed 1") # Clamp tiny rounding overshoots (such as 1.0000000000000002) back into [-1.0, 1.0]. return max(-1.0, min(1.0, correlation))✅ Submit now — all tests should pass.
Intuition & how it works
Imagine timing a daily two-leg commute: walking to the train station (X) and riding the train (Y). Variance (the average squared deviation from the mean) measures how unpredictable each duration is. If walking times and train times vary independently, their variances simply add up: Var(X + Y) = Var(X) + Var(Y). If rain slows down both your walk and the train on the same days, the bad days stack together and Var(X + Y) grows larger than Var(X) + Var(Y). If running late on the walk makes you catch a faster express train, the two swings partly cancel and Var(X + Y) shrinks below Var(X) + Var(Y). That extra gap, Var(X + Y) - Var(X) - Var(Y), equals 2 * Cov(X, Y), where covariance is the average product of their deviations from the mean.
When Var(Y) is missing, the naive guess is to subtract Var(X + Y) - Var(X) and try to infer the relationship anyway. That fails because Var(X + Y) - Var(X) = Var(Y) + 2 * Cov(X, Y) mixes two completely unknown quantities (Var(Y) and Cov(X, Y)) inside a single equation, so identifiability (pinning down a unique answer from the inputs) breaks down. Worse, Pearson correlation (covariance divided by both standard deviations so it lies in [-1, 1]) also needs sqrt(Var(Y)) in the denominator.
Once all three variances are known, the algebra unlocks cleanly. Walking through Example 1 (var_sum=52, var_x=9, var_y=25):
- The individual variances are
Var(X) = 9(std_x = 3) andVar(Y) = 25(std_y = 5), whose uncorrelated baseline sum is9 + 25 = 34. - Subtracting the individual variances from
Var(X + Y) = 52and halving givesCov(X, Y) = (52 - 9 - 25) / 2 = 9.0. - Dividing by
std_x * std_y = 3 * 5 = 15yieldsCorr(X, Y) = 9.0 / 15 = 0.6.
Complexity
- Time:
O(1). We perform a fixed number of arithmetic comparisons, subtractions, divisions, and twomath.sqrtcalls regardless of the magnitude of the numbers. - Space:
O(1). We store only a handful of scalar floats (covariance,std_x,std_y,correlation) with no auxiliary data structures.
Edge cases
var_y is None(Part 1): ReturnsNone. Any non-negativevar_sumandvar_xcan be realized by someY, and for anyvar_sum > 0infinitely many correlations fit. (As a neat mathematical curiosity, at the single boundary pointvar_sum == 0withvar_x > 0,X + Yis constant soY = c - Xwould technically haveCorr = -1, while for the general identifiability promptvar_y is Nonealways signals missingVar(Y)and returnsNone.)- Boundary correlations (
-1.0and+1.0): By the Cauchy-Schwarz inequality (which guarantees|Cov(X, Y)| <= sd_x * sd_y),Var(X + Y)must lie in[(sd_x - sd_y)^2, (sd_x + sd_y)^2]. Whenvar_x = 2andvar_y = 3,var_sum = (sqrt(2) + sqrt(3))^2rounds tocorrelation = 1.0000000000000002in IEEE-754 floating point, so we allow a1e-9tolerance before raisingValueErrorand clamp the final return value to[-1.0, 1.0]. - Zero variance (
var_x == 0orvar_y == 0): A constant variable has zero covariance with every variable, soVar(X + Y)must equalVar(X) + Var(Y). When consistent (such as(4, 4, 0)or(0, 0, 0)), correlation is0 / 0and we returnNone; when inconsistent (such as(6, 4, 0)), we raiseValueError. - Negative or non-finite inputs: Variances cannot be negative or infinite/NaN; checking
math.isfinitefirst preventsNaNfrom slipping past< 0comparisons. - Extreme scales (
1e200or1e-300): Computingmath.sqrt(var_x) * math.sqrt(var_y)separately avoids overflowingvar_x * var_ytoinfor underflowing it to0.0.
Common mistakes
- Assuming independence or equal variances when
Var(Y)is omitted: SettingCov(X, Y) = 0orVar(Y) = Var(X)invents a second equation that was never provided; without that extra assumption,Corr(X, Y)is not identifiable. - Returning covariance instead of correlation:
(Var(X + Y) - Var(X) - Var(Y)) / 2still has units ofX * Yand must be divided bysqrt(Var(X)) * sqrt(Var(Y)). - Dropping the factor of
2: Expanding(X + Y)^2produces2 * X * Y, so forgetting/ 2doubles every estimated correlation. - Treating zero variance as zero correlation: When
Var(Y) = 0,Cov(X, Y)is0, notCorr(X, Y). Dividing0by0leaves correlation undefined (None). - Skipping feasibility checks: Inputs like
(var_sum=30, var_x=4, var_y=9)yield(30 - 13) / (2 * 2 * 3) = 17 / 12 > 1, which cannot come from any real probability distribution and should raiseValueError.
Follow-up questions
- How does the identity and resulting correlation formula change if Var(X - Y) is provided instead of Var(X + Y)? Expanding the variance of a difference reverses the sign on the cross-term:
Var(X - Y) = Var(X) + Var(Y) - 2 * Cov(X, Y). Solving for covariance givesCov(X, Y) = (Var(X) + Var(Y) - Var(X - Y)) / 2, soCorr(X, Y) = (Var(X) + Var(Y) - Var(X - Y)) / (2 * sqrt(Var(X)) * sqrt(Var(Y))). Notice that sinceX - Y = X + (-Y)andCorr(X, -Y) = -Corr(X, Y), feedingVar(X - Y)intoderive_correlationreturns-Corr(X, Y); if you have bothVar(X + Y)andVar(X - Y), covariance simplifies directly to(Var(X + Y) - Var(X - Y)) / 4. - What happens to covariance, correlation, and input consistency when Y is a constant with Var(Y) = 0? Zero variance means
Yequals its mean with probability1, soY - E[Y] = 0everywhere, forcingCov(X, Y) = 0and requiringVar(X + Y) == Var(X)for the inputs to be consistent. Becausesqrt(Var(Y)) = 0sits in the denominator of Pearson correlation,Corr(X, Y)is0 / 0(undefined): our implementation returnsNonewhenVar(X + Y) == Var(X)and raisesValueErrorotherwise, mirroring standard statistical libraries (numpy.corrcoefreturnsnanandstatistics.correlationraisesStatisticsError). - If you estimate the three variances from finite data samples rather than true population parameters, how can sampling noise affect the result? When all three sample variances are computed on the exact same complete paired dataset with the same denominator (
nor Bessel's correctionn - 1, which divides byn - 1for an unbiased sample variance), the sum identity holds identically on the sample and recovers sample Pearsonr, whose sampling error decays as1 / sqrt(n)(via Fisher's z-transformationatanh(r), which is approximately normal with standard error1 / sqrt(n - 3)on bivariate normal data). By contrast, ifVar(X + Y),Var(X), andVar(Y)are estimated across different subsamples or unsynchronized windows, their estimation errors fail to cancel and(var_sum_hat - var_x_hat - var_y_hat) / 2can easily breach[-1, 1], particularly near±1or on small samples.
Follow-up questions
- How does the identity and resulting correlation formula change if Var(X - Y) is provided instead of Var(X + Y)?
- What happens to covariance, correlation, and input consistency when Y is a constant with Var(Y) = 0?
- If you estimate the three variances from finite data samples rather than true population parameters, how can sampling noise affect the result?
Similar questions
- Computing Pearson Correlation from Component and Sum Variances
- Handling an Inconclusive A/B Test Readout
- Ad Serving Economics, Mixture Variance, and Waiting Times
- Target Bankroll Probability with Biased Flips
- Statistical Inference and Sizing for Trip Cancellations
- Impact of Dataset Duplication on OLS and Large-Sample Inference