Computing Pearson Correlation from Component and Sum Variances

Easy · Statistics & Math · Data Scientist · Technical Screen

Problem Statement

Consider two real-valued random variables X and Y defined on the same probability space. You are given the variance of their sum var_sum = Var(X + Y), the variance of the first variable var_x = Var(X), and optionally the variance of the second variable var_y = Var(Y) (None when Var(Y) is unavailable).

Implement correlation_from_variances(var_sum, var_x, var_y) to compute the Pearson correlation coefficient between X and Y according to the following rules:

  1. Missing second variance (var_y is None): Knowing only Var(X + Y) and Var(X) leaves both Var(Y) and Cov(X, Y) unknown inside a single equation, so correlation cannot be uniquely pinned down. After validating that var_sum and var_x are finite and non-negative, return None.
  2. Known positive variances (var_x > 0 and var_y > 0): Use the sum-variance relation Var(X + Y) = Var(X) + Var(Y) + 2 * Cov(X, Y) to solve for Cov(X, Y) and normalize by sqrt(Var(X)) * sqrt(Var(Y)) (note that in the equal-variance case Var(Y) == Var(X), this simplifies to Var(X + Y) / (2 * Var(X)) - 1).
  3. Zero-variance variables (var_x == 0 or var_y == 0): A constant random variable has zero covariance with every variable, forcing Var(X + Y) == Var(X) + Var(Y) (up to floating-point relative tolerance 1e-9). If that equality holds, return None because Pearson correlation divides by zero; otherwise raise a ValueError.
  4. Input validation and feasibility: Raise a ValueError if any supplied variance is NaN, infinite, or negative, or if the implied correlation magnitude exceeds 1 beyond benign floating-point rounding (1e-9). Clamp tiny rounding overshoots at the ±1 boundaries into [-1.0, 1.0].

Examples

Example 1

Input:  var_sum = 57, var_x = 16, var_y = 25
Output: 0.4

Walk-through: Subtracting the individual variances from the sum variance gives 2 * Cov(X, Y) = 57 - 16 - 25 = 16, so Cov(X, Y) = 8.0. Dividing by sqrt(16) * sqrt(25) = 4 * 5 = 20 yields 8.0 / 20 = 0.4.

Example 2

Input:  var_sum = 29, var_x = 16, var_y = 25
Output: -0.3

Walk-through: Because 29 is below the uncorrelated sum 16 + 25 = 41, the variables partly offset one another: Cov(X, Y) = (29 - 41) / 2 = -6.0, giving -6.0 / (4 * 5) = -0.3.

Example 3

Input:  var_sum = 27, var_x = 9, var_y = 9
Output: 0.5

Walk-through: Here X and Y share equal variance V = 9, so Var(X + Y) / (2 * V) - 1 = 27 / 18 - 1 = 0.5.

Example 4

Input:  var_sum = 20, var_x = 9, var_y = None
Output: None

Walk-through: Both 20 and 9 are finite and non-negative, and because var_y is None, infinitely many (Var(Y), Cov(X, Y)) pairs fit the inputs, so the function returns None.

Constraints

  • All provided float arguments may span extreme IEEE-754 scales (e.g., 1e-300 through 1e308), as well as 0.0, negative numbers, inf, or nan.
  • Avoid intermediate floating-point overflow or underflow when multiplying or summing extreme variances.
  • Any returned float correlation must lie in [-1.0, 1.0].

Step-by-step walkthrough

  1. Understand the statistical definitions and contract

    Before touching algebra, let's pin down the four statistical quantities in plain English:

    • Variance (Var(X)): the average squared distance of X from its mean — always >= 0.
    • Standard deviation (sd_x = sqrt(Var(X))): the square root of variance, measuring spread in the original units of X.
    • Covariance (Cov(X, Y)): the average product (X - mean_x) * (Y - mean_y) — positive when X and Y rise together, negative when one rises as the other falls, and 0 when one is constant or they are uncorrelated.
    • Pearson correlation (rho): covariance rescaled by both standard deviations so it always sits between -1 and +1:
    rho = Cov(X, Y) / (sd_x * sd_y)
    

    Our function correlation_from_variances(var_sum, var_x, var_y) receives Var(X + Y), Var(X), and optionally Var(Y) (None if unknown), and obeys four clean rules:

    1. If var_y is None (Part 1), return None because rho cannot be uniquely determined.
    2. If all three positive variances are consistent (Parts 2 and 3), return rho in [-1.0, 1.0].
    3. If var_x == 0 or var_y == 0 on consistent inputs, return None because dividing by 0 leaves rho undefined.
    4. If any variance is negative, non-finite (NaN/inf), or violates mathematical bounds, raise ValueError.
  2. Part 1: Why Var(X + Y) and Var(X) alone are not enough

    The fundamental identity linking the variance of a sum to individual variances is:

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

    Why is there a 2 * Cov(X, Y) term? Because squaring (X - mean_x) + (Y - mean_y) expands just like (a + b)^2 = a^2 + b^2 + 2ab!

    If you are only told Var(X + Y) and Var(X), you have one equation with two unknowns (Var(Y) and Cov(X, Y)). Look how the exact same inputs Var(X) = 1 and Var(X + Y) = 4 produce three completely opposite correlations:

    Choice of Y                     Var(X)   Var(Y)   Cov(X, Y)   Var(X + Y)   rho
    -----------------------------   ------   ------   ---------   ----------   -----
    Y = X        (moves with X)       1        1         +1           4        +1.0
    Y indep of X (unrelated)          1        3          0           4         0.0
    Y = -3 * X   (opposes X)          1        9         -3           4        -1.0
    

    So Part 1's answer is No: we additionally need Var(Y) (or another second-moment piece like Var(X - Y) plus Var(Y)). Notice that any var_sum >= 0 and var_x >= 0 can be realized by some Y, so after checking finiteness and non-negativity, var_y is None immediately returns None:

        # Phase 1: Validate known variances (reject NaN, Inf, and negative values).
        if not math.isfinite(var_sum) or not math.isfinite(var_x):
            raise ValueError("variances must be finite")
        if var_sum < 0 or var_x < 0:
            raise ValueError("a variance cannot be negative")
    
        # Part 1: Without Var(Y), one equation has two unknowns (Var(Y) and Cov(X, Y)), so rho is unidentifiable.
        if var_y is None:
            return None
        if not math.isfinite(var_y) or var_y < 0:
            raise ValueError("variances must be finite and non-negative")
    
  3. Part 2: Derive correlation when Var(Y) is also known

    Once Var(Y) is also given, Cov(X, Y) is the only unknown left in the sum identity! Solve for Cov(X, Y) in two algebra steps, then divide by sd_x * sd_y:

    Step 1:  Var(X + Y) = Var(X) + Var(Y) + 2 * Cov(X, Y)
    
    Step 2:  Cov(X, Y)  = (Var(X + Y) - Var(X) - Var(Y)) / 2
                        = 0.5 * Var(X + Y) - 0.5 * Var(X) - 0.5 * Var(Y)
    
    Step 3:  rho        = Cov(X, Y) / (sqrt(Var(X)) * sqrt(Var(Y)))
    

    Read this formula intuitively using Var(X) + Var(Y) as the uncorrelated baseline:

    • Var(X + Y) > Var(X) + Var(Y) -> X and Y amplify each other -> rho > 0.
    • Var(X + Y) == Var(X) + Var(Y) -> X and Y are uncorrelated -> rho == 0.
    • Var(X + Y) < Var(X) + Var(Y) -> X and Y partially cancel -> rho < 0.
        # Phase 3 (Parts 2 & 3): Solve Var(X + Y) = Var(X) + Var(Y) + 2 * Cov(X, Y) for Cov(X, Y).
        # Halving each term before subtracting prevents `-var_x - var_y` from overflowing near 1e308.
        cov = 0.5 * var_sum - 0.5 * var_x - 0.5 * var_y
    
        # Take separate square roots so `var_x * var_y` never overflows at 1e200 or underflows at 1e-300.
        sd_x = math.sqrt(var_x)
        sd_y = math.sqrt(var_y)
        rho = cov / (sd_x * sd_y)
    
  4. Part 3: Simplify the equal-variance special case

    In the special case Var(Y) = Var(X) = V (with V > 0), both standard deviations equal sqrt(V), so sd_x * sd_y = V:

    rho = (Var(X + Y) - V - V) / (2 * V)
        = (Var(X + Y) - 2 * V) / (2 * V)
        = Var(X + Y) / (2 * V) - 1
    

    Sanity-check the three landmark cases:

    Y = -X  (perfect cancellation):   Var(X + Y) = 0      ->  0 / (2V) - 1  = -1.0
    Y indep (uncorrelated):           Var(X + Y) = 2 * V  -> 2V / (2V) - 1  =  0.0
    Y = +X  (perfect reinforcement):  Var(X + Y) = 4 * V  -> 4V / (2V) - 1  = +1.0
    

    Our general Part 2 formula already evaluates to this exact number whenever var_x == var_y, so no separate code path is needed.

  5. Handle degenerate, inconsistent, and extreme float inputs

    A production-ready implementation must guard against four tricky numerical cases:

    1. Impossible variance triples (|rho| > 1): By the Cauchy-Schwarz inequality (a mathematical bound guaranteeing |Cov(X, Y)| <= sd_x * sd_y), Var(X + Y) must always lie inside:
    [(sd_x - sd_y)^2,  (sd_x + sd_y)^2]
    
    For `Var(X) = 4` (`sd_x = 2`) and `Var(Y) = 9` (`sd_y = 3`), `Var(X + Y)` must sit in `[1, 25]`; `var_sum = 30` implies `rho = 1.417`, which no random variables can ever have, so we raise `ValueError`.
    
    1. Floating-point rounding at ±1: Valid inputs like var_x = 2, var_y = 3, var_sum = (sqrt(2) + sqrt(3))^2 can evaluate to rho = 1.0000000000000002 in 64-bit float. Allowing a tiny TOLERANCE = 1e-9 before raising and then clamping max(-1.0, min(1.0, rho)) keeps exact boundary cases valid.
    2. Zero variance (var_x == 0 or var_y == 0): A constant never varies from its mean, so its covariance with anything is 0, forcing Var(X + Y) == Var(X) + Var(Y). If var_sum disagrees, raise ValueError; otherwise return None (0 / 0 is undefined).
    3. Preventing 1e308 overflow and 1e-300 underflow: Writing 0.5 * var_sum - 0.5 * var_x - 0.5 * var_y prevents -var_x - var_y from overflowing to -inf when var_x = var_y = 1e308, and taking math.sqrt(var_x) * math.sqrt(var_y) separately prevents var_x * var_y from overflowing at 1e200 or underflowing to 0.0 at 1e-300.
        # Phase 2: Degenerate zero-variance check.
        # A constant variable has Cov(X, Y) = 0, so Var(X + Y) must equal Var(X) + Var(Y), while rho is 0/0 (None).
        if var_x == 0 or var_y == 0:
            expected_sum = var_x + var_y
            scale = max(var_sum, expected_sum)
            if abs(var_sum - expected_sum) > TOLERANCE * scale:
                raise ValueError("inconsistent: a constant variable has zero covariance")
            return None
    
        # Phase 3 (Parts 2 & 3): Solve Var(X + Y) = Var(X) + Var(Y) + 2 * Cov(X, Y) for Cov(X, Y).
        # Halving each term before subtracting prevents `-var_x - var_y` from overflowing near 1e308.
        cov = 0.5 * var_sum - 0.5 * var_x - 0.5 * var_y
    
        # Take separate square roots so `var_x * var_y` never overflows at 1e200 or underflows at 1e-300.
        sd_x = math.sqrt(var_x)
        sd_y = math.sqrt(var_y)
        rho = cov / (sd_x * sd_y)
    
        # Phase 4: Enforce Cauchy-Schwarz (|rho| <= 1) up to float rounding, then clamp into [-1.0, 1.0].
        if abs(rho) > 1.0 + TOLERANCE:
            raise ValueError("inconsistent variances: |rho| would exceed 1")
        return max(-1.0, min(1.0, rho))
    
  6. Walk through the four examples

    Example  (var_sum, var_x, var_y)  cov = 0.5*(sum - x - y)   sd_x * sd_y  Result
    -------  -----------------------  ------------------------  -----------  ------
    1        (57, 16, 25)             0.5*(57 - 16 - 25) = 8.0  4 * 5 = 20    0.4
    2        (29, 16, 25)             0.5*(29 - 16 - 25) = -6.0 4 * 5 = 20   -0.3
    3        (27,  9,  9)             0.5*(27 -  9 -  9) = 4.5  3 * 3 = 9     0.5
    4        (20,  9, None)           var_y missing -> unidentifiable         None
    

    In Examples 1 and 2, var_sum sits inside the valid range [(4 - 5)^2, (4 + 5)^2] = [1, 81], landing above the uncorrelated sum 16 + 25 = 41 in Example 1 (rho = +0.4) and below 41 in Example 2 (rho = -0.3).

  7. Full solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    import math
    
    # Small relative slack so exact |rho| = 1 inputs nudged by float rounding (e.g. 1.0000000000000002) pass.
    TOLERANCE = 1e-9
    
    
    def correlation_from_variances(
        var_sum: float, var_x: float, var_y: Optional[float]
    ) -> Optional[float]:
        # Phase 1: Validate known variances (reject NaN, Inf, and negative values).
        if not math.isfinite(var_sum) or not math.isfinite(var_x):
            raise ValueError("variances must be finite")
        if var_sum < 0 or var_x < 0:
            raise ValueError("a variance cannot be negative")
    
        # Part 1: Without Var(Y), one equation has two unknowns (Var(Y) and Cov(X, Y)), so rho is unidentifiable.
        if var_y is None:
            return None
        if not math.isfinite(var_y) or var_y < 0:
            raise ValueError("variances must be finite and non-negative")
    
        # Phase 2: Degenerate zero-variance check.
        # A constant variable has Cov(X, Y) = 0, so Var(X + Y) must equal Var(X) + Var(Y), while rho is 0/0 (None).
        if var_x == 0 or var_y == 0:
            expected_sum = var_x + var_y
            scale = max(var_sum, expected_sum)
            if abs(var_sum - expected_sum) > TOLERANCE * scale:
                raise ValueError("inconsistent: a constant variable has zero covariance")
            return None
    
        # Phase 3 (Parts 2 & 3): Solve Var(X + Y) = Var(X) + Var(Y) + 2 * Cov(X, Y) for Cov(X, Y).
        # Halving each term before subtracting prevents `-var_x - var_y` from overflowing near 1e308.
        cov = 0.5 * var_sum - 0.5 * var_x - 0.5 * var_y
    
        # Take separate square roots so `var_x * var_y` never overflows at 1e200 or underflows at 1e-300.
        sd_x = math.sqrt(var_x)
        sd_y = math.sqrt(var_y)
        rho = cov / (sd_x * sd_y)
    
        # Phase 4: Enforce Cauchy-Schwarz (|rho| <= 1) up to float rounding, then clamp into [-1.0, 1.0].
        if abs(rho) > 1.0 + TOLERANCE:
            raise ValueError("inconsistent variances: |rho| would exceed 1")
        return max(-1.0, min(1.0, rho))
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of two random variables X and Y as two ocean waves meeting on the water, where variance (the average squared distance from the mean) measures each wave's energy. If two unrelated waves of energies 16 and 25 meet randomly, their combined wave X + Y has baseline energy 16 + 25 = 41. When the combined wave carries more energy than 41 (say 57), their peaks are lining up together (positive correlation); when it is calmer than 41 (say 29), the two waves are partially canceling each other out (negative correlation).

If you are only given Var(X + Y) and Var(X), trying to write a formula for correlation fails immediately because one equation (Var(X + Y) = Var(X) + Var(Y) + 2 * Cov(X, Y)) cannot solve for two unknowns (Var(Y) and Cov(X, Y)). Even once Var(Y) is provided, a bare one-liner (var_sum - var_x - var_y) / (2 * sqrt(var_x * var_y)) breaks on edge inputs: it crashes with division by zero on constant variables, returns impossible numbers like 1.42 on inconsistent variances, falsely rejects valid rho = 1 inputs nudged to 1.0000000000000002 by float rounding, and overflows var_x * var_y at 1e200 (or -var_x - var_y at 1e308).

Walking through Example 1 (var_sum=57, var_x=16, var_y=25) step by step:

  1. Extract covariance: Covariance measures how X and Y co-move in raw units; subtracting the uncorrelated baseline 16 + 25 = 41 and halving gives Cov(X, Y) = 0.5 * 57 - 0.5 * 16 - 0.5 * 25 = 8.0.
  2. Compute standard deviations: Each standard deviation (the square root of variance) is sd_x = sqrt(16) = 4 and sd_y = sqrt(25) = 5.
  3. Normalize and validate: Pearson correlation divides covariance by sd_x * sd_y = 20, giving rho = 8.0 / 20 = 0.4. Because |0.4| <= 1 (satisfying the Cauchy-Schwarz inequality, which guarantees |Cov(X, Y)| <= sd_x * sd_y), 0.4 is valid and returned directly.

Complexity

  • Time: O(1). Every call performs a fixed handful of finiteness checks, floating-point multiplications/subtractions, two square roots, and one division, with no loops or recursion.
  • Space: O(1). Only a constant number of scalar floating-point variables (cov, sd_x, sd_y, rho) are allocated.

Edge cases

  • Missing Var(Y) (var_y is None): Returns None after verifying var_sum and var_x are finite and non-negative; any var_sum >= 0 is achievable by choosing a suitable Y, so (var_sum, var_x) alone is never inconsistent.
  • Equal variances (Var(X) = Var(Y) = V): Simplifies algebraically to rho = Var(X + Y) / (2 * V) - 1, mapping Var(X + Y) linearly from [0, 4V] onto [-1, +1].
  • Zero variance (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) (otherwise ValueError is raised), and rho is undefined (None) because its denominator is 0.
  • Boundary rounding at rho = ±1: Inputs like var_x = 2, var_y = 3, var_sum = (sqrt(2) + sqrt(3))^2 can round to 1.0000000000000002; checking abs(rho) > 1.0 + 1e-9 and clamping to [-1.0, 1.0] accepts exact collinearity while rejecting genuine impossible triples.
  • Extreme float scales (1e-300 to 1e308) and NaN/inf: Separate sqrt calls and pre-halved 0.5 * var terms prevent intermediate overflow/underflow, and math.isfinite catches NaN and inf before comparisons silently pass.

Common mistakes

  • Claiming Var(X + Y) and Var(X) suffice when Var(Y) is omitted: Without Var(Y), Var(X) = 1 and Var(X + Y) = 4 fits rho = +1 (Y = X), rho = 0 (Var(Y) = 3 independent), and rho = -1 (Y = -3X).
  • Forgetting the factor of 2 on Cov(X, Y): Writing Var(X + Y) = Var(X) + Var(Y) + Cov(X, Y) makes every computed correlation twice as large as the true value.
  • Dividing by Var(X) * Var(Y) or (Var(X) + Var(Y)) / 2: Correlation normalizes by sqrt(Var(X)) * sqrt(Var(Y)); the arithmetic mean (Var(X) + Var(Y)) / 2 only matches the geometric mean when Var(X) == Var(Y).
  • Skipping consistency checks: Blindly returning rho = 1.42 for (30, 4, 9) ignores that Var(X + Y) must lie inside [(sd_x - sd_y)^2, (sd_x + sd_y)^2] = [1, 25].
  • Computing math.sqrt(var_x * var_y) as a single product: 1e200 * 1e200 overflows to inf (returning rho = 0.0 instead of 1.0!), while 1e-200 * 1e-200 underflows to 0.0 and raises ZeroDivisionError.

Follow-up questions

  • How does the calculation behave when one of the two random variables has zero variance? A zero-variance variable takes a single constant value with probability 1, so it never deviates from its mean and its covariance with any random variable is 0. That leaves rho = 0 / 0 undefined (so our function returns None, whereas NumPy returns nan), and it enforces a strict consistency check: Var(X + Y) must equal Var(X) + Var(Y), or else we raise ValueError.
  • If you were given the variance of the difference X - Y in place of the sum X + Y, how would the expression for correlation change? Replacing +Y with -Y flips the sign on the cross-term: Var(X - Y) = Var(X) + Var(Y) - 2 * Cov(X, Y). Rearranging and normalizing yields rho = (Var(X) + Var(Y) - Var(X - Y)) / (2 * sd_x * sd_y) — here, strong positive correlation shrinks Var(X - Y) because X and Y move together and cancel in the difference! Better yet, if you know both Var(X + Y) and Var(X - Y) for equal-variance variables, Var(X) cancels out completely to give rho = (Var(X + Y) - Var(X - Y)) / (Var(X + Y) + Var(X - Y)).
  • Could you construct two concrete pairs of random variables that share identical values of Var(X) and Var(X + Y) yet exhibit completely different correlations? Let X take +1 and -1 with probability 1/2 each, so Var(X) = 1, and target Var(X + Y) = 4. Pair A sets Y = X: then X + Y = 2X has Var(X + Y) = 4 with rho = +1. Pair B sets Y = -3X: then X + Y = -2X still has Var(X + Y) = (-2)^2 * 1 = 4, yet Y moves strictly opposite to X with rho = -1!
  • What practical issues arise when plugging noisy sample variance estimates into this identity instead of exact population variances? When Var(X + Y), Var(X), and Var(Y) are computed from the exact same complete paired sample with the same denominator (n or n - 1), the algebraic identity still holds on the sample and matches sample Pearson r inside [-1, 1]. If instead the three variances come from different lookback windows, missing-data subsets, or asynchronous ticks (common in market data), independent estimation noise no longer cancels and can push the implied correlation outside [-1, 1]. To quantify sampling uncertainty from n paired observations, apply the Fisher z-transform (z = 0.5 * ln((1 + r) / (1 - r)), a nonlinear mapping that makes sample correlation roughly normal with standard error 1 / sqrt(n - 3)), build a confidence interval in z-space, and transform back to [-1, 1].

Follow-up questions

Similar questions

More Jefferies interview questions

All 2 Jefferies questions →