KatInterview

Calculate Mean and Variance for the Sum of Two Variables

Arrays & HashingAuto-graded · 17 test cases
EasyAuto-gradedArrays & Hashingstatisticsprobabilitymath

Last updated

Compute the expected value and total variance of the combined sum of two random variables given their individual means, variances, and covariance.

Given the individual statistics of two random variables $X$ and $Y$, write a function to calculate the expected value and variance of their sum $Z = X + Y$.

You are provided with:

  • mean_x: The expected value of $X$, $\mathbb{E}[X]$
  • variance_x: The variance of $X$, $\text{Var}(X)$
  • mean_y: The expected value of $Y$, $\mathbb{E}[Y]$
  • variance_y: The variance of $Y$, $\text{Var}(Y)$
  • covariance: The covariance between $X$ and $Y$, $\text{Cov}(X, Y)$

Return a dictionary containing two keys:

  • "expectation": The expected value $\mathbb{E}[X + Y]$
  • "variance": The variance $\text{Var}(X + Y)$

Constraints

  • -1000.0 <= mean_x, mean_y <= 1000.0
  • 0.0 <= variance_x, variance_y <= 1000.0
  • -1000.0 <= covariance <= 1000.0
  • The covariance provided is valid for the given variances.

Examples

Example 1

Input: sum_expectation_variance(3, 4, 5, 9, 2)

Output: {'expectation': 8, 'variance': 17}

Example 2

Input: sum_expectation_variance(3, 4, 5, 9, 0)

Output: {'expectation': 8, 'variance': 13}

Example 3

Input: sum_expectation_variance(-2, 1.5, 7, 2.5, -1)

Output: {'expectation': 5, 'variance': 2}

Hints

Hint 1

Recall the linearity property of expectation: E[X + Y] = E[X] + E[Y].

Hint 2

Recall the expansion formula for variance: Var(X + Y) = Var(X) + Var(Y) + 2 * Cov(X, Y).

Hint 3

When X and Y are independent, their covariance is 0, which reduces the variance equation to Var(X) + Var(Y).