Sample Covariance Between Two Variables

Basics
BasicsCovarianceGoogleMetaJane Street

Problem

Implement sample_covariance(x, y) returning Cov(x,y)=1n−1∑i=1n(xi−xˉ)(yi−yˉ)\text{Cov}(x, y) = \frac{1}{n-1}\sum_{i=1}^n (x_i - \bar{x})(y_i - \bar{y}) as a Python float.

Why It Matters: Covariance measures whether two features move together (> 0), inversely (< 0), or independently (≈ 0)—forming the building block of PCA, correlation, and OLS regression.

Function Signature

import numpy as np

def sample_covariance(x, y) -> float:

Sample Input & Output

Example 1: Perfectly Positively Related

Input:

x = [1.0, 2.0, 3.0], y = [2.0, 4.0, 6.0]

Expected Output:

2.0

Explanation: Centered products are (-1)(-2) + (0)(0) + (1)(2) = 4.0; dividing by n - 1 = 2 gives 2.0.

Example 2: Inversely Related

Input:

x = [1.0, 2.0, 3.0], y = [9.0, 6.0, 3.0]

Expected Output:

-3.0

Explanation: As x rises, y falls by 3×, giving negative covariance -3.0.

Constraints & Edge Cases

  • Input length >= 2.
  • Return a Python float.
  • Divide by n - 1 (sample covariance), not n.
  • Both sequences have equal length n >= 2.

Constraints & Evaluation Criteria

  • Input length `>= 2`.
  • Return a Python `float`.

Hints

Python 3
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
[1,2,3] & [2,4,6]
Expected Output / Criteria
2.0