Calculate Mean and Variance for the Sum of Two Variables
Arrays & HashingAuto-graded · 17 test casesLast 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.00.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).
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To compute the expected value and variance of the sum of two random variables $X$ and $Y$:
-
Expectation of the Sum: By the linearity of expectation, the expected value of a sum of any two random variables is simply the sum of their individual expected values: $$\mathbb{E}[X + Y] = \mathbb{E}[X] + \mathbb{E}[Y]$$
-
Variance of the Sum: The variance of the sum takes into account the variances of both variables plus twice their covariance: $$\text{Var}(X + Y) = \text{Var}(X) + \text{Var}(Y) + 2 \cdot \text{Cov}(X, Y)$$
If $X$ and $Y$ are uncorrelated or independent, $\text{Cov}(X, Y) = 0$, simplifying the formula to $\text{Var}(X) + \text{Var}(Y)$.
Complexity Analysis
- Time Complexity: $\mathcal{O}(1)$ — direct arithmetic operations.
- Space Complexity: $\mathcal{O}(1)$ — fixed output dictionary structure.
def sum_expectation_variance(
mean_x: float,
variance_x: float,
mean_y: float,
variance_y: float,
covariance: float,
) -> dict[str, float]:
return {
"expectation": mean_x + mean_y,
"variance": variance_x + variance_y + 2 * covariance,
}