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):

  1. Identifiability check (var_y is None): When only Var(X + Y) and Var(X) are supplied, the identity Var(X + Y) = Var(X) + Var(Y) + 2 * Cov(X, Y) leaves two unknown quantities (Var(Y) and Cov(X, Y)) in a single equation, and the denominator sqrt(Var(X)) * sqrt(Var(Y)) is also unknown. After checking that var_sum and var_x are finite and non-negative, return None.
  2. Closed-form derivation (var_y provided): When var_x > 0 and var_y > 0, isolate covariance as Cov(X, Y) = (Var(X + Y) - Var(X) - Var(Y)) / 2 and return Cov(X, Y) / (sqrt(Var(X)) * sqrt(Var(Y))).
  3. Degenerate zero-variance handling (var_x == 0 or var_y == 0): A zero-variance variable is constant and has zero covariance with every variable, requiring Var(X + Y) == Var(X) + Var(Y) (within floating-point relative tolerance 1e-9). Return None when consistent because correlation is undefined (0 / 0), or raise a ValueError if Var(X + Y) disagrees.
  4. Domain and feasibility checks: Raise a ValueError if any supplied variance is non-finite (NaN or inf) 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.0 and tiny sub-unit magnitudes (1e-300) up to 1e200, or invalid values (< 0, inf, nan).
  • Avoid overflowing or underflowing var_x * var_y when computing the denominator at extreme scales.
  • Every returned numeric correlation must satisfy -1.0 <= result <= 1.0.

Step-by-step walkthrough

  1. 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 variable X from its mean E[X]. It measures how spread out X is, and it can never be negative.
    • Standard deviation (sd_x = sqrt(Var(X))) puts that spread back into the original units of X.
    • Covariance (Cov(X, Y)) is the average product (X - E[X]) * (Y - E[Y]). It is positive when X and Y tend to rise together, negative when one rises as the other falls, and 0 when 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) receives var_sum = Var(X + Y), var_x = Var(X), and var_y = Var(Y) (or None when Var(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 whether Corr(X, Y) can be determined from Var(X + Y) and Var(X) alone.
    • Part 2 (var_y is given): compute Corr(X, Y) when the variances are valid and positive, return None when a zero variance leaves correlation undefined, and raise ValueError when the inputs are mathematically impossible.
  2. Derive the variance-of-a-sum identity

    Why does Var(X + Y) tell us anything about how X and Y move together? Write dx = X - E[X] and dy = Y - E[Y] for the deviations from each mean. Because E[X + Y] = E[X] + E[Y], the deviation of X + Y from its mean is simply dx + dy.

    Squaring (dx + dy) with the ordinary algebra rule (a + b)^2 = a^2 + b^2 + 2ab and 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 + Y has three pieces:

    |<------------------ Var(X + Y) ------------------>|
    |---- Var(X) ----|---- Var(Y) ----|-- 2*Cov(X,Y) --|
    

    When Cov(X, Y) > 0, the 2 * Cov(X, Y) term stretches Var(X + Y) above Var(X) + Var(Y). When Cov(X, Y) < 0, the two variables partly cancel each other out and shrink Var(X + Y) below Var(X) + Var(Y).

  3. 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) and Var(X), while Var(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) and Cov(X, Y)), so infinitely many pairs (Var(Y), Cov(X, Y)) produce the exact same Var(X + Y) and Var(X). Worse still, even if someone handed us Cov(X, Y), the formula Cov(X, Y) / (sqrt(Var(X)) * sqrt(Var(Y))) still requires sqrt(Var(Y)) in the denominator.

    A concrete counterexample proves that any correlation in [-1, 1] can fit the same two numbers. Fix Var(X) = 4 and Var(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.0
    

    All three choices have Var(X) = 4 and Var(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 return None whenever var_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 None
    
  4. Part 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 in Var(X + Y) = Var(X) + Var(Y) + 2 * Cov(X, Y). Subtract Var(X) and Var(Y) from both sides and divide by 2:

    2 * Cov(X, Y) = Var(X + Y) - Var(X) - Var(Y)
        Cov(X, Y) = (Var(X + Y) - Var(X) - Var(Y)) / 2
    

    When Var(X) > 0 and Var(Y) > 0, dividing Cov(X, Y) by sqrt(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) and math.sqrt(var_y) separately before multiplying them. If we wrote math.sqrt(var_x * var_y) instead, large inputs like var_x = var_y = 1e200 would overflow var_x * var_y to inf (silently turning any correlation into 0.0), and tiny inputs like 1e-300 would underflow var_x * var_y to 0.0 (crashing with ZeroDivisionError).

        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)
    
  5. 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:

    1. Zero variance (var_x == 0 or var_y == 0): A variable with zero variance is a constant, and a constant never varies with anything, so Cov(X, Y) must be 0. That means Var(X + Y) must equal Var(X) + Var(Y) (allowing a tiny relative tolerance 1e-9 for float rounding). If covariance is non-zero, the three numbers contradict each other and we raise ValueError. If they are consistent, correlation is still 0 / 0 (undefined), so we return None.
    2. The [-1, 1] range check: By the Cauchy-Schwarz inequality (which guarantees |Cov(X, Y)| <= sd_x * sd_y for every pair of random variables), Corr(X, Y) must lie between -1 and +1. Equivalently, Var(X + Y) must sit between (sd_x - sd_y)^2 and (sd_x + sd_y)^2. If abs(correlation) > 1.0 + TOLERANCE, no random variables (X, Y) could ever have those three variances, so we raise ValueError. Otherwise we clamp correlation to [-1.0, 1.0] in case float rounding produced 1.0000000000000002 at a true boundary of 1.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))
    
  6. 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.5
    

    In Example 1, Var(X + Y) = 52 exceeds the uncorrelated sum 9 + 25 = 34, yielding Corr(X, Y) = +0.6. In Example 3, Var(X + Y) = 49 sits well below 25 + 64 = 89, yielding Corr(X, Y) = -0.5.

  7. 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):

  1. The individual variances are Var(X) = 9 (std_x = 3) and Var(Y) = 25 (std_y = 5), whose uncorrelated baseline sum is 9 + 25 = 34.
  2. Subtracting the individual variances from Var(X + Y) = 52 and halving gives Cov(X, Y) = (52 - 9 - 25) / 2 = 9.0.
  3. Dividing by std_x * std_y = 3 * 5 = 15 yields Corr(X, Y) = 9.0 / 15 = 0.6.

Complexity

  • Time: O(1). We perform a fixed number of arithmetic comparisons, subtractions, divisions, and two math.sqrt calls 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): Returns None. Any non-negative var_sum and var_x can be realized by some Y, and for any var_sum > 0 infinitely many correlations fit. (As a neat mathematical curiosity, at the single boundary point var_sum == 0 with var_x > 0, X + Y is constant so Y = c - X would technically have Corr = -1, while for the general identifiability prompt var_y is None always signals missing Var(Y) and returns None.)
  • Boundary correlations (-1.0 and +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]. When var_x = 2 and var_y = 3, var_sum = (sqrt(2) + sqrt(3))^2 rounds to correlation = 1.0000000000000002 in IEEE-754 floating point, so we allow a 1e-9 tolerance before raising ValueError and clamp the final return value to [-1.0, 1.0].
  • Zero variance (var_x == 0 or var_y == 0): A constant variable has zero covariance with every variable, so Var(X + Y) must equal Var(X) + Var(Y). When consistent (such as (4, 4, 0) or (0, 0, 0)), correlation is 0 / 0 and we return None; when inconsistent (such as (6, 4, 0)), we raise ValueError.
  • Negative or non-finite inputs: Variances cannot be negative or infinite/NaN; checking math.isfinite first prevents NaN from slipping past < 0 comparisons.
  • Extreme scales (1e200 or 1e-300): Computing math.sqrt(var_x) * math.sqrt(var_y) separately avoids overflowing var_x * var_y to inf or underflowing it to 0.0.

Common mistakes

  • Assuming independence or equal variances when Var(Y) is omitted: Setting Cov(X, Y) = 0 or Var(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)) / 2 still has units of X * Y and must be divided by sqrt(Var(X)) * sqrt(Var(Y)).
  • Dropping the factor of 2: Expanding (X + Y)^2 produces 2 * X * Y, so forgetting / 2 doubles every estimated correlation.
  • Treating zero variance as zero correlation: When Var(Y) = 0, Cov(X, Y) is 0, not Corr(X, Y). Dividing 0 by 0 leaves 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 raise ValueError.

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 gives Cov(X, Y) = (Var(X) + Var(Y) - Var(X - Y)) / 2, so Corr(X, Y) = (Var(X) + Var(Y) - Var(X - Y)) / (2 * sqrt(Var(X)) * sqrt(Var(Y))). Notice that since X - Y = X + (-Y) and Corr(X, -Y) = -Corr(X, Y), feeding Var(X - Y) into derive_correlation returns -Corr(X, Y); if you have both Var(X + Y) and Var(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 Y equals its mean with probability 1, so Y - E[Y] = 0 everywhere, forcing Cov(X, Y) = 0 and requiring Var(X + Y) == Var(X) for the inputs to be consistent. Because sqrt(Var(Y)) = 0 sits in the denominator of Pearson correlation, Corr(X, Y) is 0 / 0 (undefined): our implementation returns None when Var(X + Y) == Var(X) and raises ValueError otherwise, mirroring standard statistical libraries (numpy.corrcoef returns nan and statistics.correlation raises StatisticsError).
  • 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 (n or Bessel's correction n - 1, which divides by n - 1 for an unbiased sample variance), the sum identity holds identically on the sample and recovers sample Pearson r, whose sampling error decays as 1 / sqrt(n) (via Fisher's z-transformation atanh(r), which is approximately normal with standard error 1 / sqrt(n - 3) on bivariate normal data). By contrast, if Var(X + Y), Var(X), and Var(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) / 2 can easily breach [-1, 1], particularly near ±1 or on small samples.

Follow-up questions

Similar questions

More Jefferies interview questions

All 2 Jefferies questions →